In this article, we will discuss how to convert Stream into an ArrayList in Java 1.8 version using Stream API
Stream to ArrayList :
- Using Collectors.toList()
- 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:
- Java 8 – Conversion of Arrays to Stream
- Java 8 – Conversion of Stream to Arrays
- Java 8 – Convert List to Stream
- Java 8 – Convert Stream to List
- Java 8 – Convert Stream to ArrayList
- Java 8 – Convert Stream to LinkedList
- Java 8 – Convert Stream to HashSet
- Java 8 – Convert Stream to LinkedHashSet
- Java 8 – Convert Stream to TreeSet
References:
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList–
- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toCollection-java.util.function.Supplier-
Happy Coding !!
Happy Learning !!