# collect() method

In 
Published 2023-06-10

This tutorial explains how we can use collect() method with Streams in Java.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

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));
	}
}

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