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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Trending

  • Scaling Microservices With Docker and Kubernetes on Production
  • Rust, WASM, and Edge: Next-Level Performance
  • Advancing Your Software Engineering Career in 2025
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  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?

By 
Marco Molteni user avatar
Marco Molteni
·
Mar. 26, 19 · Presentation
Likes (21)
Comment
Save
Tweet
Share
32.1K 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.

Related

  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 2: Understanding Neo4j
  • How to Introduce a New API Quickly Using Micronaut
  • Introducing Graph Concepts in Java With Eclipse JNoSQL

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!