Reputation: 6345
I have a list of strings on which i want to want to write the distinct set of strings in a file as well as convert it to UUIDs and store it another variable. Is it possible with Java 8 lambdas and how?
The reason i asked for two collectors is to avoid running it into a second loop.
Upvotes: 5
Views: 1252
Reputation: 39536
This is possible in Java 12 which introduced Collectors.teeing
:
public static <T, R1, R2, R>
Collector<T, ?, R> teeing(Collector<? super T, ?, R1> downstream1,
Collector<? super T, ?, R2> downstream2,
BiFunction<? super R1, ? super R2, R> merger);
Returns a Collector that is a composite of two downstream collectors. Every element passed to the resulting collector is processed by both downstream collectors, then their results are merged using the specified merge function into the final result.
Example:
Entry<Long, Long> entry = Stream
.of(1, 2, 3, 4, 5)
.collect(teeing(
filtering(i -> i % 2 != 0, counting()),
counting(),
Map::entry));
System.out.println("Odd count: " + entry.getKey());
System.out.println("Total count: " + entry.getValue());
Upvotes: 3
Reputation: 100159
As @Holger noted I wrote a pairing collector as an answer to another question which aggregates two collectors. Such collector is readily available now in my StreamEx library: MoreCollectors.pairing
. Similar collector is available in jOOL library as well.
Upvotes: 2