How to use the collect() method in Stream API in Java 9?


The collect() method in Stream API collects all objects from a stream object and stored in the type of collection. The user has to provide what type of collection the results can be stored. We specify the collection type using the Collectors Enum. There are different types and different operations can be present in the Collectors Enum, but most of the time we can use Collectors.toList(), Collectors.toSet(), and Collectors.toMap().

Syntax

<R, A> R collect(Collector<? super T,A,R> collector)

Example

import java.util.*;
import java.util.stream.*;

public class StreamCollectMethodTest {
   public static void main(String args[]) {
      List<String> list = List.of("a", "b", "c", "d", "e", "f", "g", "h", "i");

      List<String> subset1 = list.stream()
                                 .takeWhile(s -> !s.equals("e"))
                                 .collect(Collectors.toList());
      System.out.println(subset1);

      List<String> subset2 = list.stream()
                                 .dropWhile(s -> !s.equals("e"))
                                 .collect(Collectors.toList());
      System.out.println(subset2);

      List<Integer> numbers = Stream.iterate(1, i -> i <= 10, i -> i+1)
                                    .collect(Collectors.toList());
      System.out.println(numbers);
   }
}

Output

[a, b, c, d]
[e, f, g, h, i]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

raja
raja

e

Updated on: 27-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements