[英]Convert Stream of Collection<String[]> to List<String>[]
I have a piece of code: 我有一段代码:
table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)
The last step: .map(hash::get)
returns Collection<String[]>
. 最后一步:
.map(hash::get)
返回Collection<String[]>
。 and as a result I need to collect all of that to List. 结果,我需要将所有这些收集到List中。
.collect(Collectors.toList())
returns List> what is expected, but 返回List>预期的结果,但是
.flatMap(Stream::of).collect(Collectors.toList()).collect(Collectors.toList())
returns the same result. 返回相同的结果。
You can use flatMap like so : 您可以像这样使用flatMap:
List<String> list = table.stream()
.map(row -> hash.get(row[keyColumnNumber]))
.filter(Objects::nonNull)
.flatMap(Arrays::stream)
.collect(Collectors.toList());
If 如果
table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)
returns a Stream<Collection<String[]>>
and you require a List<String[]>
, you do need flatMap
: 返回
Stream<Collection<String[]>>
并且您需要List<String[]>
,您确实需要flatMap
:
List<String[]> result = table.stream()
.filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber])
.map(hash::get) // Stream<Collection<String[]>>
.flatMap(Collection::stream) // Stream<String[]>
.collect(Collectors.toList()); // List<String[]>
It should be possible to join the map
and flatMap
calls into a single flatMap
, as Aomine commented: 正如Aomine所说,应该有可能将
map
和flatMap
调用加入到一个flatMap
。
List<String[]> result = table.stream()
.filter(row -> !hash.containsKey(row[keyColumnNumber]))
.flatMap(row -> hash.get(row[keyColumnNumber]).stream()) // Stream<String[]>
.collect(Collectors.toList()); // List<String[]>
try this. 尝试这个。 i hope it can solve...
我希望它可以解决...
List<String> list = table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber])
.flatMap(x -> Arrays.stream(hash.get()))//<<-----------------
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.