Stepan
Stepan

Reputation: 1431

Return a set of all keys in a collection of maps

Is there a built in Java method that takes several maps as arguments and returns a set of all keys in these maps?

Something like

public static Set<String> getKeys(Map<String, ?> ... arg2){

    Set<String> result = new HashSet<>();        
    for (Map<String, ?> map : arg2) {
        for (Map.Entry<String, ?> entry : map.entrySet()) {
            String key = entry.getKey();
            result.add(key);
        }            
    }
    return result;
}

Upvotes: 4

Views: 1658

Answers (2)

MatWdo
MatWdo

Reputation: 1740

You can use Java 8 and streams.

public static Set<String> getKeys(Map<String, ?> ... arg2){
    return Arrays.stream(arg2)
            .map(Map::keySet)
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());
}

Upvotes: 3

Gikkman
Gikkman

Reputation: 762

Not that I know of, no. But let's have some fun with Java 8 streams, shall we?

private Set<String> keys(Map<String, ?>... maps) {
    return Arrays.stream(maps).flatMap((map) -> map.keySet().stream()).collect(Collectors.toSet());
}

Upvotes: 6

Related Questions