数据
1 2 3 4 5 6
| 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
1 2 3 4 5 6 7 8
| Map<Integer, List<String>> collect = userList.stream().collect( Collectors.toMap(User::getId,
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反其道而行之,它默认给抛异常,抛异常…所以要重写第三个参数
1
| Map<Integer, String> collect2 = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername, (oldVal, currVal) -> currVal));
|
2. 将User的id作为key,Dept中的值取自User,Dept为List作为值
1 2 3 4 5 6 7
| 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的话就会报错,重写一个方法
1 2 3 4
| Map<Integer, List<User>> collect4 = userList.stream().collect( CollectionsUtil.groupingByWithNullKeys(User::getId));
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public static class CollectionsUtil {
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的数据
1 2 3 4 5 6 7 8 9 10
| Map<Integer, User> collect8 = userList.stream(). filter(item -> ObjectUtil.isNotNull(item.getId())). collect(
Collectors.groupingBy(User::getId, Collectors.collectingAndThen( Collectors.maxBy( Comparator.comparing(User::getAge)), Optional::get)));
|