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?
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.
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.
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());
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With