【发布时间】:2018-04-05 22:35:20
【问题描述】:
我对 java 8 完全陌生,我有点不清楚如何继续。
我在 Java 7 中有一个 Map <String, List<value>>,我只会在键上使用 for 循环并将列表收集到一个列表中。
但是,我希望能够在 8 中做到这一点。 我所拥有的是:
List<Value> newList = resultMap.entrySet().stream()
.flatMap( e -> e.getValue().stream())
.map( // get the value in the list)
.collect(Collectors.toList())
但是,在这种情况下,我无法从 value 所属的 hashmap 中知道 key。
在执行上述操作时,如何获取 hashmap 的键值?
【问题讨论】:
-
for 循环中的代码是什么样的?我想知道您如何处理密钥,因为您没有将其放入结果列表中。
-
对于他们的密钥,您将使用
keySet而不是entrySet;请说明resultMap的类型以及您期望在newList中的类型。 -
List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList()); -
@CardinalSystem OP 说 Map 的类型应该类似于
Map<?, List<Value>>所以你不能直接在 Map 的值上使用Collectors.toList()。 -
钥匙丢弃后无法取回。您的
flatMaplambda 必须保留您以后想要的任何信息。
标签: java dictionary streaming flatmap