Use keySet() to Get a Set of Keys From a HashMap in Java The simplest way to get the keys from a HashMap in Java is to invoke the keySet() method on your HashMap object. It returns a set containing all the keys from the HashMap .
Get keys from value in HashMap To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue().
HashMap containsKey() Method in Java HashMap. containsKey() method is used to check whether a particular key is being mapped into the HashMap or not. It takes the key element as a parameter and returns True if that element is mapped in the map.
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;
}
You can retrieve all of the Map
's keys using the method keySet()
. Now, if what you need is to get a key given its value, that's an entirely different matter and Map
won't help you there; you'd need a specialized data structure, like BidiMap
(a map that allows bidirectional lookup between key and values) from Apache's Commons Collections - also be aware that several different keys could be mapped to the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With