Java Stream: is there a way to iterate taking two elements a time instead of one?

后端 未结 5 1100
无人共我
无人共我 2020-12-09 16:22

Let\'s say we have this stream

Stream.of(\"a\", \"b\", \"err1\", \"c\", \"d\", \"err2\", \"e\", \"f\", \"g\", \"h\", \"err3\", \"i\", \"j\");
5条回答
  •  无人及你
    2020-12-09 16:58

    Other approach with Collector.of and List> as structure to collect pairs. First collect to List>:

    List> collect = Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")
            .collect(
                    Collector.of(
                            LinkedList::new,
                            (a, b) -> {
                                if (b.startsWith("err"))
                                    a.add(new ArrayList<>(List.of(b)));
                                else if (!a.isEmpty() && a.getLast().size() == 1)
                                    a.getLast().add(b);
                            },
                            (a, b) -> { throw new UnsupportedOperationException(); }
                    )
            );
    

    Then it can be transform to map

    Map toMap = collect.stream().filter(l -> l.size() == 2)
            .collect(Collectors.toMap(
                    e -> e.get(0),
                    e -> e.get(1))
            );
    

    Or all in one with Collectors.collectingAndThen

    Map toMap = Stream.of("a", "b", "err1", "c", "d", "err2", "e", "f", "g", "h", "err3", "i", "j")
            .collect(Collectors.collectingAndThen(
                    Collector.of(
                            LinkedList>::new,
                            (a, b) -> {
                                if (b.startsWith("err"))
                                    a.add(new ArrayList<>(List.of(b)));
                                else if (!a.isEmpty() && a.getLast().size() == 1)
                                    a.getLast().add(b);
                            },
                            (a, b) -> { throw new UnsupportedOperationException(); }
                    ), (x) -> x.stream().filter(l -> l.size() == 2)
                            .collect(Collectors.toMap(
                                    e -> e.get(0),
                                    e -> e.get(1))
                            )
            ));
    

提交回复
热议问题