Search code examples
javahashmap

Retrieving all the keys from a list of maps


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)?


Solution

  • This should work.

    • stream the list of maps
    • flatten the streams of the keySets
    • collect.into a set.
    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());
    
    }