How To Get ArrayList From Stream in Java 8 | Code Factory
1 min readApr 22, 2020
Reference Link : Link
Donate : Link
1. Using Collectors.toList()
method
ArrayListFromStream.java
package com.codeFactory;import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;/**
* @author code.factory
*
*/
public class ArrayListFromStream {public static void main(String... args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
ArrayList<Integer> arrayList = getArrayListFromStream(stream);
System.out.println("ArrayList : " + arrayList);
}
private static <T> ArrayList<T> getArrayListFromStream(Stream<T> stream) {
return new ArrayList<T>(stream.collect(Collectors.toList()));
}
}
Output :
ArrayList : [1, 2, 3, 4, 5]
2. Using Collectors.toCollection()
method
ArrayListFromStream.java
package com.codeFactory;import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.stream.Stream;/**
* @author code.factory
*
*/
public class ArrayListFromStream {public static void main(String... args) {
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
ArrayList<Integer> arrayList = getArrayListFromStream(stream);
System.out.println("ArrayList : " + arrayList);
}
private static <T> ArrayList<T> getArrayListFromStream(Stream<T> stream) {
return new ArrayList<T>(stream.collect(Collectors.toCollection(ArrayList::new)));
}
}
Output :
ArrayList : [1, 2, 3, 4, 5]