简体   繁体   中英

Is there any way to extract Map's values?

I try to extract values from the below data type. Map<String, Map<String, Integer>>, The sample data is like this.

  1. ("aaa", Map("bbb",333) )
  2. ("ddd", Map("ccc",444) )

Result that I want

HashMap 
key : bbb, value : 333 
key : ccc, value : 444

I tried

mapData.values().stream()
       .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue))

but got failed. Is there any good way to extract the values part as Map in the nested Map ?

You need to flatMap your entries of the inner map -

Map<String, Integer> output = map.values().stream()
        .flatMap(m -> m.entrySet().stream())
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Simple way is:

Map<String,Integer> map = new HashMap<>();
mapData.values().forEach(map::putAll);

or

mapData.values().stream().collect(HashMap::new, HashMap::putAll,Map::putAll);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM