Streams – collect() operation

The Stream collect() method in Java is a terminal operation and it can be used to accumulate elements of any Stream into a Collection.

What is a terminal operation in Java Streams?

  • Terminal operation collects the data for us.
  • Terminal operation starts the whole stream pipeline.
  • We can not execute any other operation after the terminal operation. It’s the last operation in a stream pipeline.

The collect() method takes in an input of type Collector.

The Collector class provides many useful methods like toList(), which you already saw in the past examples.
We use the toList() method to collect the result of a Stream into the List.

Let’s explore some of the most used methods of the Collector class in our examples.

Java Stream collect() operation – examples

Example 1:
Collectors.joining() – performs the String concatenation on the elements in the stream.
There are 3 overloaded versions of the method:

class Test {

  public static void main(String[] args) {
    List<String> words = new ArrayList<>(Arrays.asList("Hello", "World", "of", "Java!"));
    
    String result = words.stream().collect(Collectors.joining());

    System.out.println(result);

    String resultWithDelimiters = words.stream().collect(Collectors.joining("-")); // delimiter

    System.out.println(resultWithDelimiters);

    String resultWithDelimitersAndPrefixAndSuffix = words.stream().collect(Collectors.joining("-", "(", ")")); // delimiter, prefix, suffix

    System.out.println(resultWithDelimitersAndPrefixAndSuffix);
  }
}

Output: HelloWorldofJava! Hello-World-of-Java! (Hello-World-of-Java!)


Example 2:
Collectors.counting() – returns the total number of processed elements from the stream.

class Test {

  public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

    long count = numbers.stream()
            .filter(num -> num % 2 == 0)
            .collect(Collectors.counting());

    System.out.println("Total count of even numbers: " + count);
  }
}

Output: Total count of even numbers: 5


Example 3:
Collectors.mapping() – applies transformation function first, and then collects the data into any type of a Collection.

In this example, the program will take a list of names, convert each element to upper case, and then will create a new List.

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("James", "Tom", "Megan", "Steve", "Joan"));

    List<String> namesInUpperCase = names.stream()
            .collect(Collectors.mapping(name -> name.toUpperCase(), Collectors.toList()));

    System.out.println(namesInUpperCase);
  }
}

Output: [JAMES, TOM, MEGAN, STEVE, JOAN]


Example 4:
Collections.toList() and Collections.toSet() functions collect the elements of a stream into a list or a set.

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("James", "Tom", "Megan", "Steve", "Joan", "Megan"));

    List<String> namesList = names.stream().collect(Collectors.toList());

    Set<String> namesSet = names.stream().collect(Collectors.toSet());

    System.out.println(namesList);

    System.out.println(namesSet);
  }
}

Output: [James, Tom, Megan, Steve, Joan, Megan] [Megan, Joan, Tom, James, Steve]


In the next lesson, we will cover the Collectors.groupingBy() method.


That’s it!

 

Leave a Reply

Your email address will not be published.