DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Java
  4. Java 12: The Teeing Collector

Java 12: The Teeing Collector

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

Marco Molteni user avatar by
Marco Molteni
·
Mar. 26, 19 · Presentation
Like (20)
Save
Tweet
Share
28.77K Views

Join the DZone community and get the full member experience.

Join For Free

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!

Java (programming language)

Published at DZone with permission of Marco Molteni. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Cloud-Native Application Networking
  • PostgreSQL: Bulk Loading Data With Node.js and Sequelize
  • Three SQL Keywords in QuestDB for Finding Missing Data
  • Best Practices for Writing Clean and Maintainable Code

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: