![](/img/trans.png)
[英]Convert List<List<String>> to Stream<Stream<String>>
[英]Convert Stream of Collection<String[]> to List<String>[]
我有一段代碼:
table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)
最后一步: .map(hash::get)
返回Collection<String[]>
。 結果,我需要將所有這些收集到List中。
.collect(Collectors.toList())
返回List>預期的結果,但是
.flatMap(Stream::of).collect(Collectors.toList()).collect(Collectors.toList())
返回相同的結果。
您可以像這樣使用flatMap:
List<String> list = table.stream()
.map(row -> hash.get(row[keyColumnNumber]))
.filter(Objects::nonNull)
.flatMap(Arrays::stream)
.collect(Collectors.toList());
如果
table.stream().filter(row -> !hash.containsKey(row[keyColumnNumber]))
.map(row -> row[keyColumnNumber]).map(hash::get)
返回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[]>
正如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[]>
嘗試這個。 我希望它可以解決...
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.