Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java 12: The Teeing Collector

DZone 's Guide to

Java 12: The Teeing Collector

Want to learn more about the newest collector to Java 12?

· Java Zone ·
Free Resource

In this article, we look at a new collector introduced in Java 12. This new feature was not announced in the official JEP because it was a minor change request with title Create Collector, which merges the results of two other collectors.

Documentation

Click here to check out the Collectors#teeing official documentation. According to the documentation, it:

"...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."

Method 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:

Image title

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

Teeing originated from the plumbing tee! According to Wikipeedia, " 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.

Image title

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

Click here fore the list of alternatives evaluated by the Java Core Devs.

Use Case Examples

I collected three different examples with different levels of complexity.

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

Guest List

We extract two different types of information from a list (stream) of objects. Every guest has to accept the invitation and can bring family.

We want to know who confirmed the reservation and the total number of participants (including guests and family members).

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.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 = 11 }


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 into 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

Perhaps, you saw a similar example circulating on blogs that merge sum and count to the average. That example doesn't require Teeing, and you can just use AverageInt and a simple collector.

The following example uses features from Teeing to return the two 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 two values — you have to create it yourself.

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

Everything About Java 12

You can learn more information and fun facts about Java 12 in this presentation.

Happy collecting!

Topics:
java ,java 12 ,openjdk ,jdk 12 ,functional programming ,lambda expressions ,collector#teeing

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}