Java 17 new feature: Teeing Collector

Updated:

This feature was initially introduced with Java 12, now it's available with Java 17 LTS.

Teeing Collector in action

Documentation

Fun facts

Example: Guest list example

Example: Filter names in two different lists

Example: Count and sum a stream of integers

Pitfalls

Documentation

Java Documentation: Collectors#teeing

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.

Signature

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)

Fun facts

This is a tee:
a simple tee

The etymology of teeing can help us to remember the name during our daily activity or to show our knowledge at the workplace.

Teeing is originated from the plumbing tee!

Wikipedia: ‘A tee, the most common pipe fitting, is used to combine (or divide) fluid flow.’

Linux has the tee command that splits the data! Among the authors we find Richard Stallman.

<img src="/assets/img/uploads/2019/tee_linux.webp" width="553" height="194" alt=""tee command in linux"/>

Other names proposed for this feature:
bisecting, duplexing, bifurcate, replicator, fanout, tapping, unzipping, tapping, collectionToBothAndThen, biCollecting, expanding, forking, etc.

List of the alternatives

Examples

I collected 3 different examples with different level of complexity.

You could statically import static java.util.stream.Collectors.*; to reduce the amount of written code.

Guest List

We extract 2 different type of information from a list (stream) of objects.
Every guest has to accept the invitation and can come with the family.

We want to know who is going participate and the total number of participants.

var result = 
  Stream.of( 
  // Guest(String name, boolean participating, Integer participantsNumber) 
  new Guest("Marco", true, 3), 
  new Guest("David", false, 2), 
  new Guest("Roger",true, 6)) 
  .collect(Collectors.teeing( 
    // first collector, we select only who confirmed the participation 
    Collectors.filtering(Guest::isParticipating, 
       // whe want to collect only the first name in a list 
       Collectors.mapping(o -> o.name, Collectors.toList())), 
       // second collector, we want the total number of participants 
    Collectors.filtering(Guest::isParticipating, 
        Collectors.summingInt(Guest::getParticipantsNumber)), 
       // we merge the collectors in a new Object, 
       // the values are implicitly passed 
       EventParticipation::new 
   )); 
 
  System.out.println(result); 
   
  // Result 
  // EventParticipation { guests = [Marco, Roger], 
  // total number of participants = 9 } 
 

Classes Used

class Guest { 
  private String name; 
  private boolean participating; 
  private Integer participantsNumber; 
 
  public Guest(String name, boolean participating, 
   Integer participantsNumber) { 
    this.name = name; 
    this.participating = participating; 
    this.participantsNumber = participantsNumber; 
  } 
 
  public boolean isParticipating() { 
    return participating; 
  } 
 
  public Integer getParticipantsNumber() { 
    return participantsNumber; 
  } 
} 
 
class EventParticipation { 
  private List<String> guestNameList; 
  private Integer totalNumberOfParticipants; 
 
  public EventParticipation(List<String> guestNameList, 
   Integer totalNumberOfParticipants) { 
    this.guestNameList = guestNameList; 
    this.totalNumberOfParticipants = totalNumberOfParticipants; 
} 
 
@Override 
public String toString() { 
  return "EventParticipation { " + 
    "guests = " + guestNameList + 
    ", total number of participants = " + totalNumberOfParticipants + 
    " }"; 
  }} 

Filter names in two different lists

In this example we split a stream of names in two lists according to a filter.

var result = 
  Stream.of("Devoxx", "Voxxed Days", "Code One", "Basel One", 
     "Angular Connect") 
  .collect(Collectors.teeing( 
  // first collector 
  Collectors.filtering(n -> n.contains("xx"), Collectors.toList()), 
  // second collector 
  Collectors.filtering(n -> n.endsWith("One"), Collectors.toList()), 
  // merger - automatic type inference doesn't work here 
  (List<String> list1, List<String> list2) -> List.of(list1, list2) 
  )); 
 
  System.out.println(result); // -> [[Devoxx, Voxxed Days], [Code One, Basel One]] 

Count and sum a stream of integers

Maybe you saw a similar example circulating on blogs giving merging sum and count to give the average.

That example doesn't require Teeing, you can use AverageInt and a simple collector.

The following use the features of Teeing returning the 2 values:

var result = 
  Stream.of(5, 12, 19, 21) 
    .collect(Collectors.teeing( 
      // first collector 
      Collectors.counting(), 
      // second collector 
      Collectors.summingInt(n -> Integer.valueOf(n.toString())), 
      // merger: (count, sum) -> new Result(count, sum); 
      Result::new 
  )); 
 
  System.out.println(result); // -> {count=4, sum=57} 

The Result class

class Result { 
  private Long count; 
  private Integer sum; 
 
  public Result(Long count, Integer sum) { 
    this.count = count; 
    this.sum = sum; 
  } 
   
  @Override 
  public String toString() { 
    return "{" + 
      "count=" + count + 
      ", sum=" + sum + 
    '}'; 
  }} 

Pitfalls

Map.Entry

Many examples use Map.Entry to store the result of the BiFunction.

Please don't do this, because you are not storing a Map. Java Core doesn't have a standard object to store 2 values, you have to create it by yourself.

Pair in Apache Utils uses Map.Entry, for this reason is not a valid alternative.

Everything about Java 12

You can find more information and fun facts in this presentation

https://speakerdeck.com/marcomolteni/java-12-new-features-in-action

References

This post was referenced by JetBrains in Java Annotated Monthly


WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).