How to get all values from the inner maps of a map using a common key?

 ̄綄美尐妖づ 提交于 2019-12-08 06:52:37

问题


I have a map of maps: HashMap<String, Map<DistinctCode, String>>.

I need to extract the String value from the inner maps just by using a DistinctCode. How can I do that in one line or statement?

In other words, I need a method something like this:

mapOfMap.find(distinctcode)

Is it doable in one line or statement?


回答1:


In Java 8

List<String> list = map.values().stream().map(m -> m.get(distinctcode)).filter(Objects::nonNull).collect(Collectors.toList());



回答2:


With Java 8 you can do

Set<String> strings = mapOfMaps.values().stream()
           .map(m -> m.get(distinctCode))
           .filter(v -> v != null)
           .collect(Collectors.toSet());



回答3:


DistinctCode dv = ...;

Stream<String> res = 
    mom.values().stream().map(p->p.get(dv)).filter(p->p!=null);



回答4:


A slightly different Java 8 approach without null filtering:

final Set<String> values = mapOfMaps.values().stream()
            .filter(m -> m.containsKey(distinctCode))
            .map(m -> m.get(distinctCode))
            .collect(Collectors.toSet()); //this can be simplified using a static import


来源:https://stackoverflow.com/questions/29373026/how-to-get-all-values-from-the-inner-maps-of-a-map-using-a-common-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!