Collector接口

java.util.stream.Collector

存在4个方法,分别是

举例实现1

  • toList ``` 1、创建集合 ArrayList::new 2、数据添加到容中(技术数据到容器中) List::add 3、合并2个数据到一个并返回 (left, right) -> { left.addAll(right); return left;} 4、返回最终数据 i -> (R) i

结合起来就是 public static Collector> toList() { return new CollectorImpl<>((Supplier>) ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, CH_ID); }

  1. <a name="LUU1z"></a>
  2. #### 举例实现2
  3. ```java
  4. //---生成数据
  5. final List<Project> collect = IntStream.range(0, 10)
  6. .mapToObj(x -> new Project(x, "projectName" + x))
  7. .collect(Collectors.toList());
  8. //---操作
  9. final List<String> categorys = Arrays.asList("projectName1", "projectName2");
  10. //--针对项目名字进行分组
  11. final Map<String, List<Project>> map = collect.
  12. stream()
  13. .filter(x -> StringUtils.isNotBlank(x.getProjectName()))
  14. .filter(x -> categorys.contains(x.getProjectName()))
  15. .collect(Collectors.groupingBy(Project::getProjectName));
  16. //-- 分组后进行转换
  17. final List<Project> collect1 = categorys.stream()
  18. .filter(map::containsKey)
  19. .flatMap(x -> map.getOrDefault(x, new ArrayList<>()).stream())
  20. .collect(new Ff());
  21. System.out.println(JSONObject.toJSONString(collect1));
  22. //--
  23. class Ff implements Collector<Project, Set<String>, List<Project>> {
  24. private final List<Project> projects = new ArrayList<>();
  25. @Override
  26. public Supplier<Set<String>> supplier() {
  27. return HashSet::new;
  28. }
  29. @Override
  30. public BiConsumer<Set<String>, Project> accumulator() {
  31. return (x, i) -> {
  32. if (x.add(i.getProjectName())) {
  33. projects.add(i);
  34. }
  35. };
  36. }
  37. @Override
  38. public BinaryOperator<Set<String>> combiner() {
  39. return (integers, integers2) -> {
  40. integers.addAll(integers2);
  41. return integers;
  42. };
  43. }
  44. @Override
  45. public Function<Set<String>, List<Project>> finisher() {
  46. return strings -> projects;
  47. }
  48. @Override
  49. public Set<Characteristics> characteristics() {
  50. return Collections.unmodifiableSet(EnumSet.of(Characteristics.CONCURRENT));
  51. }
  52. }