# stream() & parallelStream() methods in Collections

In 
Published 2023-06-10

This tutorial explains to you how to use stream() & parallelStream() methods with Collections. We have an example for you as well.

Before Java 8 this feature wasn't available.

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 java.util.ArrayList;

@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {

		SpringApplication.run(DemoApplication.class, args);

		//Create and define a Collection (List)
		ArrayList<String> carList = new ArrayList<>();

		// safe to use with multiple threads
		carList.add("Audi");
		carList.add("Renault");
		carList.add("Peugeot");
		carList.add("Dacia");

		// Sequential processing - ordered
		carList.stream().forEach(System.out::println);
		
		System.out.println("---------------------");
		
		// Parallel processing - unordered
		carList.parallelStream().forEach(System.out::println);
		
		System.out.println("---------------------");

		// Parallel processing - ordered
		carList.parallelStream().forEachOrdered(System.out::println);
	}
}

When I run this code I receive:

Audi
Renault
Peugeot
Dacia
---------------------
Peugeot
Dacia
Audi
Renault
---------------------
Audi
Renault
Peugeot
Dacia

Process finished with exit code 0