Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream collect arrays into one list

I'm trying to use the new stream functionality to expand a list of strings into a longer list.

segments = segments.stream() //segments is a List<String>
    .map(x -> x.split("-"))
    .collect(Collectors.toList());

This, however, yields a List<String[]>(), which of course won't compile. How do I reduce the final stream into one list?

like image 914
Nate Glenn Avatar asked Nov 12 '15 03:11

Nate Glenn


People also ask

Can we convert Stream to List in Java?

Using Collectors. Get the Stream to be converted. Collect the stream as List using collect() and Collectors. toList() methods. Convert this List into an ArrayList.

Does Stream work on arrays in Java?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.


2 Answers

Use flatMap:

segments = segments.stream() //segments is a List<String>
    .map(x -> x.split("-"))
    .flatMap(Arrays::stream)
    .collect(Collectors.toList());

You can also remove intermediate array using Pattern.splitAsStream:

segments = segments.stream() //segments is a List<String>
    .flatMap(Pattern.compile("-")::splitAsStream)
    .collect(Collectors.toList());
like image 142
Tagir Valeev Avatar answered Sep 18 '22 13:09

Tagir Valeev


You need to use flatMap:

segments = segments.stream() //segments is a List<String>
    .map(x -> x.split("-"))
    .flatMap(Stream::of)
    .collect(Collectors.toList());

Note that Stream.of(T... values) simply calls Arrays.stream(T[] array), so this code is equivalent to @TagirValeev's first solution.

like image 28
Paul Boddington Avatar answered Sep 18 '22 13:09

Paul Boddington