KunLun
KunLun

Reputation: 3225

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

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.

Upvotes: 1

Views: 387

Answers (2)

Naman
Naman

Reputation: 31888

An alternate way of collecting these could be in a Set as:

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

Upvotes: 1

Eran
Eran

Reputation: 393851

You need flatMap in order to map all the keys of all the inner Maps into a single 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>

Upvotes: 6

Related Questions