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