[英]how to convert a hashmap of list into a single list in Java 8?
I am completely new to java 8 and i am a bit unclear on how to proceed. 我是Java 8的新手,我对如何进行操作还不清楚。 i have a Map
<String, List<value>>
in Java 7, i would just use for loop on the keys and collect the List into a single list. 我在Java 7中有一个Map
<String, List<value>>
,我只会在键上使用for循环并将List收集到一个列表中。
however, i want to be able to do this in 8. what i have is: 但是,我希望能够在8中做到这一点。我所拥有的是:
List<Value> newList = resultMap.entrySet().stream()
.flatMap( e -> e.getValue().stream())
.map( // get the value in the list)
.collect(Collectors.toList())
However, in this case, i would not be able to know the key from the hashmap which the value belongs to. 但是,在这种情况下,我将无法从哈希映射中知道该值所属的键。
How can i get the value of the key for the hashmap
while doing the above? 执行上述操作时,如何获取
hashmap
的键值?
You can do something like this: 您可以执行以下操作:
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());
This creates an entry for each value in each sublist, where the key is the corresponding key for the list that value came from. 这将为每个子列表中的每个值创建一个条目,其中键是该值来自的列表的对应键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.