Skip to main content

Java 8 Stream Collect() Method with examples | Programming Blog

Java 8 stream api collect method with examples
Java 8 Stream Api Collect Method

What is collect() method in Java 8?

Collect() method of java8 stream api is terminal method. It performs a mutable reduction operation on the element of the stream.

A mutable reduction operation process the stream elements and then accumulate it into a mutable result container. Once the elements are processed, a combining function merges all the result containers to create the result.

Learn Difference between Intermediate and Terminal Operations :-

There is two variant of collect method.

  1. collect(Supplier supplier, BiConsumer accumulator, BiConsumer combiner)
  2. collect(Collector collector)
Where,
  • supplier: It is a function that creates a new mutable result container. For the parallel execution, this function may be called multiple times and it must return a fresh value each time.
  • accumulator: it is a stateless function that must fold an element into a result container.
  • combiner: It is a stateless function that accepts two partial result containers and merges them, which must be compatible with the accumulator function.

Lets see example of 1st collect method.

Example 1 :- Concat list of string using stream and parallel stream

public class CollectMethod {

    public static void main(String[] args) {

        List<String> vowels = List.of("a", "e", "i", "o", "u");

     // sequential stream - nothing to combine
     StringBuilder result = vowels.stream()
                .collect(StringBuilder::new, (x, y) -> x.append(y),
                (a, b) -> a.append(",").append(b));

     System.out.println(result.toString());

     // parallel stream - combiner is combining partial results
     StringBuilder result1 = vowels.parallelStream()
                .collect(StringBuilder::new, (x, y) -> x.append(y),
                (a, b) -> a.append(",").append(b));

      System.out.println(result1.toString());
  
    }

Output :-
aeiou
a,e,i,o,u

  • The supplier function is returning a new StringBuilder object in every call.
  • The accumulator function is appending the list string element to the StringBuilder instance.
  • The combiner function is merging the StringBuilder instances. The instances are merged with each other with a comma between them.
  • In the first case, we have a sequential stream of elements. So they are processed one by one and there is only one instance of StringBuilder. There is no use of the combiner function. That’s why the output produced is “aeiou”.
  • In the second case, we have a parallel stream of strings. So, the elements are processed parallelly and there are multiple instances of StringBuilder that are being merged by the combiner function. Hence, the output produced is “a,e,i,o,u”.

 

Now lets see second collect method.

collect(Collector collector)

Example 2 :- Collectors.toList()

Collectors.toList() method is used to convert stream into list. 

Collectors.toList() in Java 8 Stream Collect

Example 3 :- Collectors.toSet()

Collectors.toSet() method is used to convert into set.
 
Collectors.toSet() in Java 8 Stream Collect

Example 4 :- Collectors.toMap()

Collectors.toMap() method is used to convert stream into map. 

In map we have key and value, and in list we have single values so we use list values as key and values length as values.

Collectors.toMap() in Java 8 Stream Collect

Example 5 :- Collectors.toCollection

As you probably already noticed, when using toSet and toList collectors, you can't make any assumptions of their implementations. If you want to use a custom implementation, you will need to use the toCollection collector with a provided collection of your choice.

Collectors.toCollector() in Java 8 Stream Collect

Example 6 :- Collectors.counting()

Return number of value in given stream.

Collectors.counting() in Java 8 Stream Collect

Example 7 :- Collectors.maxBy() / minBy()

MaxBy/MinBy collectors return the biggest/the smallest element of a Stream according to a provided Comparator instance.

Collectors.minBy And Collectors.maxBy in Java 8 Stream Collect

Example 8 :- Collectors.collectingAndThen()

CollectingAndThen is a special collector that allows performing another action on a result straight after collecting ends.

Let's collect stream elements to a set instance and then convert the result into an immutableSet instance:

Collectors.minBy And Collectors.collectingAndThen in Java 8 Stream Collect

Example 9 :- Collectors.joining()

  1. Returns a Collector that concatenates the input elements into a String, in encounter order.
  2. Returns a Collector that concatenates the input elements, separated by the specified delimiter, in encounter order.
  3. Returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

Collectors.minBy And Collectors.joining in Java 8 Stream Collect

There are also others methods available you can check out that in java doc.

Java doc for Collectors

Other Java 8 Methods :-

 

Comments

Popular posts from this blog

Flipping the Matrix HackerRank Solution in Java with Explanation

Java Solution for Flipping the Matrix | Find Highest Sum of Upper-Left Quadrant of Matrix Problem Description : Sean invented a game involving a 2n * 2n matrix where each cell of the matrix contains an integer. He can reverse any of its rows or columns any number of times. The goal of the game is to maximize the sum of the elements in the n *n submatrix located in the upper-left quadrant of the matrix. Given the initial configurations for q matrices, help Sean reverse the rows and columns of each matrix in the best possible way so that the sum of the elements in the matrix's upper-left quadrant is maximal.  Input : matrix = [[1, 2], [3, 4]] Output : 4 Input : matrix = [[112, 42, 83, 119], [56, 125, 56, 49], [15, 78, 101, 43], [62, 98, 114, 108]] Output : 119 + 114 + 56 + 125 = 414 Full Problem Description : Flipping the Matrix Problem Description   Here we can find solution using following pattern, So simply we have to find Max of same number of box like (1,1,1,1). And ...

Sales by Match HackerRank Solution | Java Solution

HackerRank Sales by Match problem solution in Java   Problem Description : Alex works at a clothing store. There is a large pile of socks that must be paired by color for sale. Given an array of integers representing the color of each sock, determine how many pairs of socks with matching colors there are. For example, there are n=7 socks with colors socks = [1,2,1,2,1,3,2]. There is one pair of color 1 and one of color 2 . There are three odd socks left, one of each color. The number of pairs is 2 .   Example 1 : Input : n = 6 arr = [1, 2, 3, 4, 5, 6] Output : 0 Explanation : We have 6 socks with all different colors, So print 0. Example 2 : Input : n = 10 arr = [1, 2, 3, 4, 1, 4, 2, 7, 9, 9] Output : 4 Explanation : We have 10 socks. There is pair of color 1, 2, 4 and 9, So print 4. This problem easily solved by HashMap . Store all pair of socks one by one in Map and check if any pair is present in Map or not. If pair is present then increment ans variable by 1 ...