I am completely new to java 8 and i am a bit unclear on how to proceed. 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.
however, i want to be able to do this in 8. what i have is:
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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.