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

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

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