Nate Glenn
Nate Glenn

Reputation: 6744

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?

Upvotes: 6

Views: 4174

Answers (2)

Paul Boddington
Paul Boddington

Reputation: 37645

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.

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100209

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());

Upvotes: 14

Related Questions