Java thread collects arrays into one list

I am trying to use a new stream function 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, gives a List<String[]>(), which of course will not compile. How to reduce the final stream in one list?

+4
source share
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 the intermediate array with Pattern.splitAsStream:

segments = segments.stream() //segments is a List<String>
    .flatMap(Pattern.compile("-")::splitAsStream)
    .collect(Collectors.toList());
+8
source

You need to use flatMap:

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

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

+2
source

Source: https://habr.com/ru/post/1615518/


All Articles