Java Hashmap: How to Get Key from Value

Java Hashmap: How to get key from value?

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.


If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.


Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.


Since version 4.0 the official Apache Commons Collections™ library supports generics.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.

Java Map get key from value

It's not easy to get key from value in Hashtable or HashMap, as compared to getting value from key, because Hash Map or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. infact Map allows same value to be mapped against multiple keys inside HashMap, Hashtable or any other Map implementation.

        String key= null;
String value="somename";
for(Map.Entry entry: MyType.entrySet()){
if(value.equals(entry.getValue())){
key = entry.getKey();
break; //breaking because its one to one map
}
}

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".

How to get values and keys from HashMap?

To get all the values from a map:

for (Tab tab : hash.values()) {
// do something with tab
}

To get all the entries from a map:

for ( Map.Entry<String, Tab> entry : hash.entrySet()) {
String key = entry.getKey();
Tab tab = entry.getValue();
// do something with key and/or tab
}

Java 8 update:

To process all values:

hash.values().forEach(tab -> /* do something with tab */);

To process all entries:

hash.forEach((key, tab) -> /* do something with key and tab */);

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);

Output:

 Active
33

Update:
Getting first key in Java 8 or higher versions.

Optional<String> firstKey = map.keySet().stream().findFirst();
if (firstKey.isPresent()) {
String key = firstKey.get();
}

Get key from a HashMap using the value

The put method in HashMap is defined like this:

Object  put(Object key, Object value) 

key is the first parameter, so in your put, "one" is the key. You can't easily look up by value in a HashMap, if you really want to do that, it would be a linear search done by calling entrySet(), like this:

for (Map.Entry<Object, Object> e : hashmap.entrySet()) {
Object key = e.getKey();
Object value = e.getValue();
}

However, that's O(n) and kind of defeats the purpose of using a HashMap unless you only need to do it rarely. If you really want to be able to look up by key or value frequently, core Java doesn't have anything for you, but something like BiMap from the Google Collections is what you want.

Getting the key when we know the value in HashMap

This code will do that:

  public List<Object> getKeysFromValue(Map<?, ?> hm, Object value){
List <Object>list = new ArrayList<Object>();
for(Object o:hm.keySet()){
if(hm.get(o).equals(value)) {
list.add(o);
}
}
return list;
}

Java Hashmap: How to get key from value?

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.


If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.


Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.


Since version 4.0 the official Apache Commons Collections™ library supports generics.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.

Finding Key associated with max Value in a Java Map

Basically you'd need to iterate over the map's entry set, remembering both the "currently known maximum" and the key associated with it. (Or just the entry containing both, of course.)

For example:

Map.Entry<Foo, Bar> maxEntry = null;

for (Map.Entry<Foo, Bar> entry : map.entrySet())
{
if (maxEntry == null || entry.getValue().compareTo(maxEntry.getValue()) > 0)
{
maxEntry = entry;
}
}

If hashmap only contains one key, is there a way to get that key without knowing anything about it?

For a single key map just do the following:

Map<String,String> map = Map.of("A","B");
System.out.println(map.keySet().iterator().next());

prints

A

For a more populated map you can do the following:

You can get the keySet() of the map via map.keySet() and iterate thru that.

If you want to try and find a particular key associated with a value you can
get the entrySet() of the map and do something like this:

String targetVal = "some value";
for (Entry<String,String> e : map.entrySet()) {
if (e.getValue().equals(targetVal)) {
System.out.println(e.getKey());
// or
System.out.println(e);

// keep iterating since multiple keys can
// map to the same value.
}
}


Related Topics



Leave a reply



Submit