Reputation: 3225
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
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
Reputation: 393851
You need flatMap
in order to map all the keys of all the inner Map
s 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