Get keys from HashMap in Java Get keys from HashMap in Java java java

Get keys from HashMap in Java


A HashMap contains more than one key. You can use keySet() to get the set of all keys.

team1.put("foo", 1);team1.put("bar", 2);

will store 1 with key "foo" and 2 with key "bar". To iterate over all the keys:

for ( String key : team1.keySet() ) {    System.out.println( key );}

will print "foo" and "bar".


This is doable, at least in theory, if you know the index:

System.out.println(team1.keySet().toArray()[0]);

keySet() returns a set, so you convert the set to an array.

The problem, of course, is that a set doesn't promise to keep your order. If you only have one item in your HashMap, you're good, but if you have more than that, it's best to loop over the map, as other answers have done.


Check this.

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

(Use java.util.Objects.equals because HashMap can contain null)

Using JDK8+

/** * Find any key matching a value. * * @param value The value to be matched. Can be null. * @return Any key matching the value in the team. */private Optional<String> findKey(Integer value){    return team1        .entrySet()        .stream()        .filter(e -> Objects.equals(e.getValue(), value))        .map(Map.Entry::getKey)        .findAny();}/** * Find all keys matching a value. * * @param value The value to be matched. Can be null. * @return all keys matching the value in the team. */private List<String> findKeys(Integer value){    return team1        .entrySet()        .stream()        .filter(e -> Objects.equals(e.getValue(), value))        .map(Map.Entry::getKey)        .collect(Collectors.toList());}

More "generic" and as safe as possible

/** * Find any key matching the value, in the given map. * * @param mapOrNull Any map, null is considered a valid value. * @param value     The value to be searched. * @param <K>       Type of the key. * @param <T>       Type of the value. * @return An optional containing a key, if found. */public static <K, T> Optional<K> findKey(Map<K, T> mapOrNull, T value) {    return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()            .stream()            .filter(e -> Objects.equals(e.getValue(), value))            .map(Map.Entry::getKey)            .findAny());}

Or if you are on JDK7.

private String findKey(Integer value){    for(String key : team1.keySet()){        if(Objects.equals(team1.get(key), value)){            return key; //return the first found        }    }    return null;}private List<String> findKeys(Integer value){   List<String> keys = new ArrayList<String>();   for(String key : team1.keySet()){        if(Objects.equals(team1.get(key), value)){             keys.add(key);      }   }   return keys;}