#
collect() method
This tutorial explains how we can use collect() method with Streams in Java.
collect()
method receive the element from the stream and create a new desired data structures.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class as below:
DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.*;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = { 10, -22, 32, -42, 150, 165, -370 };
List<Integer> negativeNumbers = Stream.of(numbers)
// We are choosing only the negative number
.filter(x -> x < 0)
// We create a List<Integer> using these numbers
.collect(Collectors.toList());
System.out.println(negativeNumbers);
System.out.println("-----------------------");
Map<Boolean, List<Integer>> partitionedElements = Stream.of(numbers)
// We are dividing the stream elements in 2 partitions
.collect(partitioningBy(x -> x < 0));
System.out.println(partitionedElements.get(true));
System.out.println(partitionedElements.get(false));
System.out.println("-----------------------");
Integer[] numbers2 = { 10, -22, 10, 30 };
Map<Integer, Long> groupedElements = Stream.of(numbers2)
// We group the elements from the stream by their value
// When working with Classes, we can group by an attribute of the class
.collect(groupingBy(Function.identity() , Collectors.counting()));
System.out.println(groupedElements);
System.out.println(groupedElements.get(10));
}
}
- Function.identity() is a function which receive a value and return the same value.
- Instead Function.identity() we can have any Function, even a reference to a method like
.collect(groupingBy(Dish::getType))
. - If no collector is specified, the elements will be put into a
When I run this code I receive:
[-22, -42, -370]
-----------------------
[-22, -42, -370]
[10, 32, 150, 165]
-----------------------
{-22=1, 10=2, 30=1}
2
Process finished with exit code 0
When we are working with Streams, we can have:
- INTERMEDIATE operations:
filter
,map
,limit
,sorted
,peak
,distinct
,skip
,flatMap
- TERMINAL operations:
forEach
,count
,sum
,min
,collect
,reduce
,anyMatch
,noneMatch
,allMatch