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

Queen's Attack II HackerRank Solution in Java with Explanation

Queen's Attack II Problem's Solution in Java (Chessboard Problem)   Problem Description : You will be given a square chess board with one queen and a number of obstacles placed on it. Determine how many squares the queen can attack.  A queen is standing on an n * n chessboard. The chess board's rows are numbered from 1 to n, going from bottom to top. Its columns are numbered from 1 to n, going from left to right. Each square is referenced by a tuple, (r, c), describing the row r and column c, where the square is located. The queen is standing at position (r_q, c_q). In a single move, queen can attack any square in any of the eight directions The queen can move: Horizontally (left, right) Vertically (up, down) Diagonally (four directions: up-left, up-right, down-left, down-right) The queen can move any number of squares in any of these directions, but it cannot move through obstacles. Input Format : n : The size of the chessboard ( n x n ). k : The number of obstacles...

Java Hashset HackerRank Solution | Programming Blog

Java Hashset HackerRank Solution with Explanation   Problem Statement :- In computer science, a set is an abstract data type that can store certain values, without any particular order, and no repeated values. {1,2,3} is an example of a set, but {1,2,2} is not a set. Today you will learn how to use sets in java by solving this problem. You are given n pairs of strings. Two pairs (a,b) and (c,d) are identical if a = c and b = d. That also implies (a,b) is not same as (b,a). After taking each pair as input, you need to print number of unique pairs you currently have. See full problem description in HackerRank Website :- https://www.hackerrank.com/challenges/java-hashset/problem Let's see solution of problem. import java.util.HashSet; import java.util.Scanner; public class Solution {     public static void main(String[] args) {         Scanner s = new Scanner(System.in);         System.out.println("Enter tot...