简体   繁体   English

地图 <String, Map<String, String> &gt;-使用流选择值键

[英]Map<String, Map<String, String>> - Select key of value using Stream

I have this Map: 我有这张地图:

Map<String, Map<String, String>> listMap = new HashMap<>();

I want to select all distinct Keys from Map which is value in main Map : listMap.value.key 我想从Map选择所有不同的Keys ,这些Keys是主Map值: listMap.value.key

List<String> distinct = listMap.entrySet().stream()
                                .map(e -> e.getValue()) //Map<String, String>
                                //Select key of value
                                .distinct().collect(Collectors.toList());

I don't know how to select key of value of listMap . 我不知道如何选择keyvaluelistMap

You need flatMap in order to map all the keys of all the inner Map s into a single Stream : 您需要flatMap才能将所有内部Map的所有键Map到单个Stream

List<String> distinct = 
    listMap.values() // Collection<Map<String,String>>
           .stream() // Stream<Map<String,String>>
           .flatMap(map -> map.keySet().stream()) // Stream<String>
           .distinct() // Stream<String>
           .collect(Collectors.toList()); // List<String>

An alternate way of collecting these could be in a Set as: 收集这些数据的另一种方法可以在Set中:

Set<String> distinct = new LinkedHashSet<>(); // for a predictable order
listMap.values().forEach(e -> distinct.addAll(e.keySet()));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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