Java 8 Stream API - Java 9 Collectors.flatMapping rewritten in Java 8

后端 未结 2 1236
一个人的身影
一个人的身影 2021-02-05 12:19

I got in touch with a new feature since java-9 called Collectors.flatMapping that takes place as a downstream of grouping or partitioning. Such as (example taken from here):

2条回答
  •  旧巷少年郎
    2021-02-05 13:17

    For just this particular case, I guess this would be a simpler version:

    Map> map =
            list.stream()
                .collect(Collectors.toMap(
                    Collection::size,
                    x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toList())
                ));
    

    If there would be merging involved (two collections that would have the same size), I would add a merge function that is pretty trivial:

     Map> map =
            list.stream()
                .collect(Collectors.toMap(
                    Collection::size,
                    x -> x.stream().filter(y -> y % 2 == 0).collect(Collectors.toCollection(ArrayList::new)),
                    (left, right) -> {
                        left.addAll(right);
                        return left;
                    }
                ));
    

    Otherwise, I agree with Michael in this comment, this is not that hard to back-port to java-8.

提交回复
热议问题