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

Plus Minus HackerRank Solution in Java | Programming Blog

Java Solution for HackerRank Plus Minus Problem Given an array of integers, calculate the ratios of its elements that are positive , negative , and zero . Print the decimal value of each fraction on a new line with 6 places after the decimal. Example 1 : array = [1, 1, 0, -1, -1] There are N = 5 elements, two positive, two negative and one zero. Their ratios are 2/5 = 0.400000, 2/5 = 0.400000 and 1/5 = 0.200000. Results are printed as:  0.400000 0.400000 0.200000 proportion of positive values proportion of negative values proportion of zeros Example 2 : array = [-4, 3, -9, 0, 4, 1]  There are 3 positive numbers, 2 negative numbers, and 1 zero in array. Following is answer : 3/6 = 0.500000 2/6 = 0.333333 1/6 = 0.166667 Lets see solution Solution 1 import java.io.*; import java.math.*; import java.security.*; import java.text.*; import java.util.*; import java.util.concurrent.*; import java.util.function.*; import java.util.regex.*; import java.util.stream.*; import static jav...

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