Let\'s say we have this stream
Stream.of(\"a\", \"b\", \"err1\", \"c\", \"d\", \"err2\", \"e\", \"f\", \"g\", \"h\", \"err3\", \"i\", \"j\");
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))
)
));