Retrieve a List from a Stream in Java 8

Method 1

String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" };
Stream<String> stream = Stream.of(arr);

Method 2

String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" };
Stream<String> stream = Stream.of(arr);
 
ArrayList<String> list = stream.filter(x -> x.length() < 5).collect(Collectors.toCollection(ArrayList::new));

Method 3

String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk", "ghijkl" };
Stream<String> stream = Stream.of(arr).parallel();
 
ArrayList<String> list = new ArrayList<String>();
stream.forEach(list::add);

Method 4

If a stream is paralleled, the forEachOrdered() method should be used instead of forEach().

String[] arr = { "ab", "bcd", "cdef", "defgh", "efhik", "fghijk",	"ghijkl" };
Stream<String> stream = Stream.of(arr).parallel();
 
ArrayList<String> list = new ArrayList<String>();
stream.forEachOrdered(list::add);

Leave a Comment