[英]how to convert a hashmap of list into a single list in Java 8?
我是Java 8的新手,我对如何进行操作还不清楚。 我在Java 7中有一个Map <String, List<value>>
,我只会在键上使用for循环并将List收集到一个列表中。
但是,我希望能够在8中做到这一点。我所拥有的是:
List<Value> newList = resultMap.entrySet().stream()
.flatMap( e -> e.getValue().stream())
.map( // get the value in the list)
.collect(Collectors.toList())
但是,在这种情况下,我将无法从哈希映射中知道该值所属的键。
执行上述操作时,如何获取hashmap
的键值?
您可以执行以下操作:
Map<Key, List<Value>> map = ...;
List<Map.Entry<Key, Value>> list =
map.entrySet()
.stream()
.flatMap(e -> {
return e.getValue().stream()
.map(v -> new AbstractMap.SimpleEntry<>(e.getKey(), v));
})
.collect(Collectors.toList());
这将为每个子列表中的每个值创建一个条目,其中键是该值来自的列表的对应键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.