[英]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? 如何将最终流简化为一个列表?
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.