New Stream Collectors in Java 9

1. Overview

Collectors were added in Java 8 which helped accumulate input elements into mutable containers such as MapList, and Set.

In this article, we’re going to explore two new collectors added in Java 9: Collectors.filtering and Collectors.flatMapping used in combination with Collectors.groupingBy providing intelligent collections of elements.

2. Filtering Collector

The Collectors.filtering is similar to the Stream filter(); it’s used for filtering input elements but used for different scenarios. The Stream’s filter is used in the stream chain whereas the filtering is a Collector which was designed to be used along with groupingBy.

With Stream’s filter, the values are filtered first and then it’s grouped. In this way, the values which are filtered out are gone and there is no trace of it. If we need a trace then we would need to group first and then apply filtering which actually the Collectors.filtering does.

The Collectors.filtering takes a function for filtering the input elements and a collector to collect the filtered elements:

@Test
public void givenList_whenSatifyPredicate_thenMapValueWithOccurences() {
    List<Integer> numbers = List.of(1, 2, 3, 5, 5);

    Map<Integer, Long> result = numbers.stream()
      .filter(val -> val > 3)
      .collect(Collectors.groupingBy(i -> i, Collectors.counting()));

    assertEquals(1, result.size());

    result = numbers.stream()
      .collect(Collectors.groupingBy(i -> i,
        Collectors.filtering(val -> val > 3, Collectors.counting())));

    assertEquals(4, result.size());
}

3. FlatMapping Collector

The Collectors.flatMapping is similar to Collectors.mapping but has a more fine-grained objective. Both the collectors takes a function and a collector where the elements are collected but flatMapping function accepts a Stream of elements which is then accumulated by the collector.

Let’s see the following model class:

class Blog {
    private String authorName;
    private List<String> comments;
      
    // constructor and getters
}

Collectors.flatMapping lets us skip intermediate collection and write directly to a single container which is mapped to that group defined by the Collectors.groupingBy:

@Test
public void givenListOfBlogs_whenAuthorName_thenMapAuthorWithComments() {
    Blog blog1 = new Blog("1", "Nice", "Very Nice");
    Blog blog2 = new Blog("2", "Disappointing", "Ok", "Could be better");
    List<Blog> blogs = List.of(blog1, blog2);
        
    Map<String,  List<List<String>>> authorComments1 = blogs.stream()
     .collect(Collectors.groupingBy(Blog::getAuthorName, 
       Collectors.mapping(Blog::getComments, Collectors.toList())));
       
    assertEquals(2, authorComments1.size());
    assertEquals(2, authorComments1.get("1").get(0).size());
    assertEquals(3, authorComments1.get("2").get(0).size());

    Map<String, List<String>> authorComments2 = blogs.stream()
      .collect(Collectors.groupingBy(Blog::getAuthorName, 
        Collectors.flatMapping(blog -> blog.getComments().stream(), 
        Collectors.toList())));

    assertEquals(2, authorComments2.size());
    assertEquals(2, authorComments2.get("1").size());
    assertEquals(3, authorComments2.get("2").size());
}

The Collectors.mapping maps all grouped author’s comments to the collector’s container i.e. List whereas this intermediate collection is removed with flatMapping as it gives a direct stream of the comment list to be mapped to the collector’s container.

4. Conclusion

This article illustrates the use of the new Collectors introduced in Java9 i.e. Collectors.filtering() and Collectors.flatMapping() used in combination with Collectors.groupingBy().

These Collectors can also be used along with Collectors.partitioningBy() but it only creates two partitions based on conditions and the real power of the collectors isn’t leveraged; hence left out of this tutorial.

The complete source code for the code snippets in this tutorial is available over on GitHub.

Related posts:

Rest Web service: Filter và Interceptor với Jersey 2.x (P1)
Custom Thread Pools In Java 8 Parallel Streams
Overflow and Underflow in Java
Chương trình Java đầu tiên
Java Program to find the maximum subarray sum using Binary Search approach
Java Program to Implement Segment Tree
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Abstract class và Interface trong Java
A Guide to the finalize Method in Java
Dynamic Proxies in Java
Java Program to Perform the Shaker Sort
Spring @Primary Annotation
Automatic Property Expansion with Spring Boot
Spring Webflux and CORS
Consumer trong Java 8
Giới thiệu JDBC Connection Pool
Hướng dẫn Java Design Pattern – DAO
So sánh ArrayList và Vector trong Java
Java Program to Search Number Using Divide and Conquer with the Aid of Fibonacci Numbers
Java Program to Implement the Alexander Bogomolny’s UnOrdered Permutation Algorithm for Elements Fro...
Life Cycle of a Thread in Java
Java Program to Implement ConcurrentSkipListMap API
Xử lý ngoại lệ trong Java (Exception Handling)
Default Password Encoder in Spring Security 5
Java Program to Check whether Graph is Biconnected
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Construct an Expression Tree for an Postfix Expression
Lập trình mạng với java
Java Program to Check whether Graph is a Bipartite using 2 Color Algorithm
Static Content in Spring WebFlux
Java Program to Implement Quick sort
Java Program to Encode a Message Using Playfair Cipher