What is the (kind of) inverse operation to Java's Stream.flatMap()?

前端 未结 5 874
别那么骄傲
别那么骄傲 2021-02-19 05:40

The Stream.flatMap() operation transforms a stream of

a, b, c

into a stream that contains zero or more elements for each input el

5条回答
  •  无人共我
    2021-02-19 06:17

    Take a look at collapse in StreamEx

    StreamEx.of("a1", "a2", "c1", "c2", "c3").collapse((a, b) -> a.charAt(0) == b.charAt(0))
        .map(e -> e.substring(0, 1)).forEach(System.out::println);
    

    Or my fork with more function: groupBy, split, sliding...

    StreamEx.of("a1", "a2", "c1", "c2", "c3").collapse((a, b) -> a.charAt(0) == b.charAt(0))
    .map(e -> e.substring(0, 1)).forEach(System.out::println);
    // a
    // c
    
    StreamEx.of("a1", "a2", "c1", "c2", "c3").splitToList(2).forEach(System.out::println);
    // [a1, a2]
    // [c1, c2]
    // [c3]
    
    StreamEx.of("a1", "a2", "c1", "c2", "c3").groupBy(e -> e.charAt(0))
    .forEach(System.out::println);
    // a=[a1, a2]
    // c=[c1, c2, c3]
    

提交回复
热议问题