Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to collect a stream into two collectors

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.

like image 473
Whimsical Avatar asked Nov 10 '15 18:11

Whimsical


2 Answers

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());
like image 182
ZhekaKozlov Avatar answered Sep 21 '22 20:09

ZhekaKozlov


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.

like image 44
Tagir Valeev Avatar answered Sep 23 '22 20:09

Tagir Valeev