Note: This works with Java 8 or above!
In order to convert a Stream to a List, make use of the of the toList() method form the Collectors util class when collecting the Stream.
Example:
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamToListExamples {
public static void main(String[] args) {
Stream<Integer> streamOfIntegers = Stream.of(1,2,4,5,6,7,8,9,10);
//Stream -> List
List<Integer> listOfIntegers = streamOfIntegers.collect(Collectors.toList());
System.out.println(listOfIntegers);
Stream<String> streamOfStrings = Stream.of("A","B","C","D","E");
//Stream -> List
List<String> listOfStrings = streamOfStrings.collect(Collectors.toList());
System.out.println(listOfStrings);
}
}
Output:
[1, 2, 4, 5, 6, 7, 8, 9, 10]
[A, B, C, D, E]
You can download this article in various formats for your convenience. Choose from the options below:
Facing issues? Have Questions? Post them here! I am happy to answer!
- Java Jackson ObjectMapper Class with Examples
- How to add a Delay of a Few Seconds in Java Program
- Java SE JDBC Select Statement Example
- How to Word-Warp Console logs in IntelliJ
- Convert Java Array to ArrayList Code Example
- [Java] Error: Unmappable character for encoding UTF-8. Save could not be completed.
- Maven BUILD FAILURE: Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin
- How to extract Java Jar/War/Ear files in Linux
- Java: Convert String to Binary
- Java Generics: Type parameter cannot be instantiated directly
- How to Create and Run a Command Line Application using Spring Boot
- How to Convert a Java Object into an Optional with Example
- [Hibernate] The method buildSessionFactory() from the type Configuration is deprecated
- How to Set JAVA_HOME PATH to Mac .zshrc profile file
- Formatting Double in Java [Examples]
- Java 8: Stream map with Code Examples
- Fix: SyntaxError: ( was never closed [Python]
- Java Split String by Spaces
- [fix] Java JDBC SQLSyntaxErrorException: Unknown database
- Fix: SpringFramework BeanDefinitionValidationException: Could not find an init method named
- Java Date Time API: LocalDateTime get(TemporalField field) examples
- How to create Date in yyyy-MM-dd format in Java
- Java: Create Temporary Directory and File and Delete when application terminates
- Fix RabbitMQ: AuthenticationFailureException: ACCESS_REFUSED
- Run Java Code Every Second
- How to Align Text using Notepad++ - NotepadPlusPlus
- Setting and Updating AWS CLI Configuration - AWS
- How to remove username from Mac Menu Bar? - MacOS
- The default username and password for RabbitMQ - HowTos
- Installing Visual Studio Code on Raspberry Pi - HowTos
- Python Program To Calculate Simple Interest (SimpleInterest.py) - Python
- How to count the files in a directory using Bash Command - Bash
- Java Program: Find Name of the Employee with Maximum Salary using Stream API - Java