数据
List<User> userList = new ArrayList<>();
userList.add(new User(1, "aaa"));
userList.add(new User(2, "bbb"));
userList.add(new User(3, "ccc"));
userList.add(new User(2, "ddd"));
userList.add(new User(3, "eee"));
1. 将id作为map的key,相同的值合并List
Map<Integer, List<String>> collect = userList.stream().collect(
Collectors.toMap(User::getId,
// e -> Arrays.asList(e.getUsername()),会报错
e -> CollUtil.newArrayList(e.getUsername()),
(List<String> oldList, List<String> newList) -> {
oldList.addAll(newList);
return oldList;
}));
注意Arrays.asList会报错,除非用new ArrayList<>(Arrays.asList
Collectors.toMap
注意:往一个map里put一个已经存在的key,会把原有的key对应的value值覆盖,然而Java8中的Collectors.toMap反其道而行之,它默认给抛异常,抛异常...所以要重写第三个参数
Map<Integer, String> collect2 = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername, (oldVal, currVal) -> currVal));
2. 将User的id作为key,Dept中的值取自User,Dept为List作为值
Map<Integer, List<Dept>> collect3 = userList.stream().collect(
Collectors.toMap(User::getId,
r -> CollUtil.newArrayList(new Dept(r.getId(), r.getUsername())),
(List<Dept> oldList, List<Dept> newList) -> {
oldList.addAll(newList);
return oldList;
}));
3. 默认groupingBy值为null的话就会报错,重写一个方法
Map<Integer, List<User>> collect4 = userList.stream().collect(
CollectionsUtil.groupingByWithNullKeys(User::getId));
// 默认groupingBy值为null的话就会报错
// Collectors.groupingBy(User::getId));
public static class CollectionsUtil {
/**
* 重写Collectors.groupingBy,允许null key
*/
public static <T, A> Collector<T, ?, Map<A, List<T>>> groupingByWithNullKeys(Function<? super T, ? extends A> classifier) {
return Collectors.toMap(classifier, Collections::singletonList,
(List<T> oldList, List<T> newEl) -> {
List<T> newList = new ArrayList<>(oldList.size() + 1);
newList.addAll(oldList);
newList.addAll(newEl);
return newList;
});
}
}
4. collectingAndThen来转换groupingBy的数据
Map<Integer, User> collect8 = userList.stream().
//对groupingBy的数据过滤null
filter(item -> ObjectUtil.isNotNull(item.getId())).
collect(
// Collectors.groupingBy(User::getId, Collectors
Collectors.groupingBy(User::getId,
Collectors.collectingAndThen(
Collectors.maxBy(
Comparator.comparing(User::getAge)),
Optional::get)));