toMap

控制不抛Duplicate Key 异常的用法:
需要调用:

  1. public static <T, K, U>
  2. Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
  3. Function<? super T, ? extends U> valueMapper,
  4. BinaryOperator<U> mergeFunction) {
  5. return toMap(keyMapper, valueMapper, mergeFunction, HashMap::new);
  6. }
  7. @Test
  8. public void toMap() {
  9. List<Pair<String, Long>> list = new ArrayList<>();
  10. list.add(new Pair<>("v", 1L));
  11. list.add(new Pair<>("v", 2L));
  12. list.add(new Pair<>("v", 3L));
  13. list.stream()
  14. .collect(Collectors.toMap(k -> k.getKey(),
  15. v -> v.getValue()));
  16. Map<String, Long> map = list.stream()
  17. .collect(Collectors.toMap(k -> k.getKey(),
  18. v -> v.getValue(), (v1, v2) -> {
  19. System.out.println(v1);
  20. System.out.println(v2);
  21. return v2;
  22. }));
  23. System.out.println(map);
  24. }

groupingBy

  1. // 1. 定义List
  2. private List<DxCourseLabel> courseLabels;
  3. // 2. 分组: 指定Value的转换Function
  4. Map<Long, List<Long>> groupBy = this.courseLabels.stream()
  5. .collect(Collectors.groupingBy(DxCourseLabel::getLabelId,
  6. Collectors.mapping(c -> c.getCourseId(), Collectors.toList())));
  7. // 2. 分组:不指定Value的转换Function
  8. Map<Long, List<Object>> groupBy = this.courseLabels.stream()
  9. .collect(Collectors.groupingBy(DxCourseLabel::getLabelId);