I have some data stored in a list of maps
List<Map<String, Integer>> myList;
Is there an easy way to get all of the keys without going element by element and calling Map::keySet
?
Say for example I have the list ((Bob, 1), (James, 5))
where Bob and James are both keys in a map, how can I get a list of just (Bob, James)
?
This should work.
Set<String> result =
mylist.stream().flatMap(map->map.keySet().stream())
.collect(Collectors.toSet());
And here is another way that avoids flatMapping. But it does iterate across each map. MapMulti puts each key on the stream and then they are collected into a set.
result = myList.stream().<String>mapMulti((map, consumer)-> {
for (String key : map.keySet()) {
consumer.accept(key);
}}).collect(Collectors.toSet());
}