How can I perform multiple unrelated operations on elements of a single stream?
Say I have a List
composed from a text. Each string in the
You could use a custom collector for that and iterate only once:
private static Collector, List>> multiple() {
class Acc {
List strings = new ArrayList<>();
List longs = new ArrayList<>();
void add(String elem) {
if (elem.contains("of")) {
long howMany = Arrays.stream(elem.split(" ")).count();
longs.add(howMany);
}
if (elem.contains("for")) {
String result = elem.substring(elem.indexOf("for"));
strings.add(result);
}
}
Acc merge(Acc right) {
longs.addAll(right.longs);
strings.addAll(right.strings);
return this;
}
public Pair, List> finisher() {
return Pair.of(strings, longs);
}
}
return Collector.of(Acc::new, Acc::add, Acc::merge, Acc::finisher);
}
Usage would be:
Pair, List> pair = Stream.of("t of r m", "t of r m", "nice for nice nice again")
.collect(multiple());