简体   繁体   中英

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.

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM