Collectors.toList() – Convert/collect a stream to list

 310 total views,  3 views today

Welcome to Java 8 series. In this tutorial, you will learn about how to Convert/collect a stream to list using Collectors.toList().

If you would like to learn more about Java Stream operations.Please check out this link.

In this example, we will use Stream.collect() operation to perform a reduce operation on the stream of elements.i.e., we will collect the stream of elements as List.

To use Collectors.toList() in stream operations, we have to import Collectors package.

java.util.stream.Collectors

Collectors.toList() example

In this example, I have created a stream out of Array of Strings.We will be using Collectors.toList() operation to convert/collect all elements from the stream and store it in a list.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StaticReference {
	public static void main(String[] args) {

		List<String> fruits = Arrays.asList("apple", 
				"mango", 
				"pomo", 
				"banana", 
				"orange", 
				"apple", 
				"banana");

		List<String> collectedFruits = fruits.stream()
				.map(eachFruit -> eachFruit.toUpperCase())
				.collect(Collectors.toList());

		collectedFruits.forEach(System.out::println);

	}
}

Output

APPLE
MANGO
POMO
BANANA
ORANGE
APPLE
BANANA

Hope you like this article. Thanks for reading and Please leave us a comment below!

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.