Let\'s say we have this stream
Stream.of(\"a\", \"b\", \"err1\", \"c\", \"d\", \"err2\", \"e\", \"f\", \"g\", \"h\", \"err3\", \"i\", \"j\");
Things would be easier if your input is located in the random-access list. This way you can utilize good old List.subList
method like this:
List list = Arrays.asList("a", "b", "err1", "c", "d", "err2", "e",
"f", "g", "h", "err3", "i", "j");
Map map = IntStream.range(0, list.size()-1)
.mapToObj(i -> list.subList(i, i+2))
.filter(l -> l.get(0).startsWith("err"))
.collect(Collectors.toMap(l -> l.get(0), l -> l.get(1)));
The same thing could be done with already mentioned StreamEx library (written by me) in a little bit shorter manner:
List list = Arrays.asList("a", "b", "err1", "c", "d", "err2", "e",
"f", "g", "h", "err3", "i", "j");
Map map = StreamEx.ofSubLists(list, 2, 1)
.mapToEntry(l -> l.get(0), l -> l.get(1))
.filterKeys(key -> key.startsWith("err"))
.toMap();
Though if you don't want third-party dependency, the poor Stream API solution looks also not very bad.