Java 8 – Convert Stream to ArrayList

In this article, we will discuss how to convert Stream into an ArrayList in Java 1.8 version using Stream API

Stream to ArrayList :

  1. Using Collectors.toList()
  2. Using Collectors.toCollection()

1. Using Collectors.toList()

  • First, convert Stream to List using collect() method of Stream API by passing Collectors.toList() as input argument
  • Above conversion yields List and not ArrayList
  • For List to ArrayList conversion, create ArrayList object and pass above list as constructor-argument
  • Finally, print converted ArrayList elements to console

StreamToArrayListUsingCollectorsToList.java

package net.bench.resources.stream.to.list;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToArrayListUsingCollectorsToList {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to List<String>
		List<String> names = nameStream.collect(Collectors.toList());


		// 3. List<String> to ArrayList<String>
		ArrayList<String> alNames = new ArrayList<String>(names);


		// 4. print to console
		System.out.println("Stream to ArrayList : \n\n" + alNames);
	}
}

Output:

Stream to ArrayList : 

[Rajiv, Anbu, Santosh, Abdul, Lingaraj]

2. Using Collectors.toCollection()

  • Convert Stream to ArrayList using collect() method of Stream API by passing Collectors.toCollection(ArrayList::new) as input argument directly
  • Print converted ArrayList elements to console

StreamToArrayListUsingCollectorsToCollection.java

package net.bench.resources.stream.to.list;

import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamToArrayListUsingCollectorsToCollection {

	public static void main(String[] args) {

		// 1. Stream of String tokens
		Stream<String> nameStream = Stream.of(
				"Rajiv",
				"Anbu",
				"Santosh",
				"Abdul",
				"Lingaraj"
				);


		// 2. convert Stream<String> to List<String>
		ArrayList<String> names = nameStream
				.collect(Collectors.toCollection(ArrayList::new));


		// 3. print to console
		System.out.println("Stream to ArrayList : \n\n" + names);
	}
}

Output:

Stream to ArrayList : 

[Rajiv, Anbu, Santosh, Abdul, Lingaraj]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - Convert Stream to LinkedList
Java 8 - Convert List to Stream