新增CollStreamUtil.groupKeyValue(java.util.Collection<E>, java.util.function.Function<E,K>, java.util.function.Function<E,V>),用于分组时直接获取属性

This commit is contained in:
VampireAchao 2021-12-09 20:13:39 +08:00 committed by achao
parent c1e6ea8d42
commit bc8e9cd159
2 changed files with 60 additions and 1 deletions

View File

@ -13,7 +13,7 @@ import java.util.stream.Collectors;
/**
* 集合的stream操作封装
*
* @author 528910437@QQ.COM
* @author 528910437@QQ.COM VampireAchao<achao1441470436@gmail.com>
* @since 5.5.2
*/
public class CollStreamUtil {
@ -195,6 +195,45 @@ public class CollStreamUtil {
.collect(Collectors.groupingBy(key1, Collectors.toMap(key2, Function.identity(), (l, r) -> l)));
}
/**
* 将collection按照规则(比如有相同的班级id)分类成mapmap中的key为班级idvalue为班级名<br>
* <B>{@code Collection<E> -------> Map<K,List<V>> } </B>
*
* @param collection 需要分类的集合
* @param key 分类的规则
* @param value 分类的规则
* @param <E> collection中的泛型
* @param <K> map中的key类型
* @param <V> List中的value类型
* @return 分类后的map
*/
public static <E, K, V> Map<K, List<V>> groupKeyValue(Collection<E> collection, Function<E, K> key,
Function<E, V> value) {
return groupKeyValue(collection, key, value, false);
}
/**
* 将collection按照规则(比如有相同的班级id)分类成mapmap中的key为班级idvalue为班级名<br>
* <B>{@code Collection<E> -------> Map<K,List<V>> } </B>
*
* @param collection 需要分类的集合
* @param key 分类的规则
* @param value 分类的规则
* @param isParallel 是否并行流
* @param <E> collection中的泛型
* @param <K> map中的key类型
* @param <V> List中的value类型
* @return 分类后的map
*/
public static <E, K, V> Map<K, List<V>> groupKeyValue(Collection<E> collection, Function<E, K> key,
Function<E, V> value, boolean isParallel) {
if (CollUtil.isEmpty(collection)) {
return Collections.emptyMap();
}
return StreamUtil.of(collection, isParallel)
.collect(Collectors.groupingBy(key, Collectors.mapping(value, Collectors.toList())));
}
/**
* 将collection转化为List集合但是两者的泛型不同<br>
* <B>{@code Collection<E> ------> List<T> } </B>

View File

@ -149,6 +149,26 @@ public class CollStreamUtilTest {
}
@Test
public void testGroupKeyValue() {
Map<Long, List<Long>> map = CollStreamUtil.groupKeyValue(null, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupKeyValue(list, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 2, 1, "李四"));
list.add(new Student(2, 2, 1, "王五"));
map = CollStreamUtil.groupKeyValue(list, Student::getTermId, Student::getClassId);
Map<Long, List<Long>> compare = new HashMap<>();
compare.put(1L, Arrays.asList(1L, 2L));
compare.put(2L, Collections.singletonList(2L));
Assert.assertEquals(compare, map);
}
@Test
public void testTranslate2List() {
List<String> list = CollStreamUtil.toList(null, Student::getName);