简体   繁体   English

Java流将数组收集到一个列表中

[英]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. 但是,这会产生List<String[]>() ,当然不会编译。 How do I reduce the final stream into one list? 如何将最终流简化为一个列表?

Use flatMap : 使用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 : 您还可以使用Pattern.splitAsStream删除中间数组:

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

You need to use flatMap : 你需要使用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. 注意Stream.of(T... values)只调用Arrays.stream(T[] array) ,所以这段代码相当于@ TagirValeev的第一个解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM