5

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.

ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
Whimsical
  • 5,985
  • 1
  • 31
  • 39
  • 2
    Maybe [this](http://stackoverflow.com/a/30211021/2711488) is helpful. – Holger Nov 10 '15 at 18:05
  • Interesting problem, however it sounds to me like unnecessary optimisation, which will give insignificant performance improvement (given that you are writing to files) and drastically reduce the readability and maintainability of the code. – Jaroslaw Pawlak Nov 11 '15 at 11:50
  • Let's not consider significance of performance implications and just talk about if and how it is possible...Maybe not in this case, but performance improvement will not be insignificant if there are two costly collector operations...Also, readability is subjective. Some might say lambdas are not readable/maintainable. – Whimsical Nov 15 '15 at 15:41

2 Answers2

3

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());
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
2

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.

Community
  • 1
  • 1
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
  • So are you saying nothing is available out of the box on Java 8 lambdas for such a situation. – Whimsical Nov 15 '15 at 15:36
  • @Mulki, yes, no ready solution to combine two collectors exists. Well, you can simply do everything inside the single `forEach()` with side-effects. – Tagir Valeev Nov 15 '15 at 15:57