Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 991
Stepan Avatar asked Jan 05 '23 16:01

Stepan


1 Answers

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());
}
like image 56
Gikkman Avatar answered Jan 11 '23 10:01

Gikkman