Get keys from HashMap in Java

JavaData StructuresJava 6

Java Problem Overview


I have a Hashmap in Java like this:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

Then I fill it like this:

team1.put("United", 5);

How can I get the keys? Something like: team1.getKey() to return "United".

Java Solutions


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

Solution 2 - Java

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.

Solution 3 - Java

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;
}

Solution 4 - Java

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.

Solution 5 - Java

Use functional operation for faster iteration.

team1.keySet().forEach((key) -> {
      System.out.println(key);
});

Solution 6 - Java

As you would like to get argument (United) for which value is given (5) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).

Solution 7 - Java

private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr=  _map.entrySet().iterator();
		        //please check 
		        while(itr.hasNext())
		        {
		        	System.out.println("key of : "+itr.next().getKey()+" value of      Map"+itr.next().getValue());
		        }

Solution 8 - Java

foreach can be used too.

team1.forEach((key, value) -> System.out.println(key));

Solution 9 - Java

If you just need something simple and more of a verification.

public String getKey(String key)
{
    if(map.containsKey(key)
    {
        return key;
    }
    return null;
}

Then you can search for any key.

System.out.println( "Does this key exist? : " + getKey("United") );

Solution 10 - Java

To get keys in HashMap, We have keySet() method which is present in java.util.Hashmap package. ex :

Map<String,String> map = new Hashmap<String,String>();
map.put("key1","value1");
map.put("key2","value2");
    
// Now to get keys we can use keySet() on map object
Set<String> keys = map.keySet();

Now keys will have your all keys available in map. ex: [key1,key2]

Solution 11 - Java

A solution can be, if you know the key position, convert the keys into an String array and return the value in the position:

public String getKey(int pos, Map map) {
    String[] keys = (String[]) map.keySet().toArray(new String[0]);

    return keys[pos];
}

Solution 12 - Java

Try this simple program:

public class HashMapGetKey {
   
public static void main(String args[]) {
      
      // create hash map
     
       HashMap map = new HashMap();
      
      // populate hash map

      map.put(1, "one");
      map.put(2, "two");
      map.put(3, "three");
      map.put(4, "four");

      // get keyset value from map
      
Set keyset=map.keySet();
      
      // check key set values

      System.out.println("Key set values are: " + keyset);
   }    
}

Solution 13 - Java

public class MyHashMapKeys {
     
    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first", "FIRST INSERTED");
        hm.put("second", "SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        Set<String> keys = hm.keySet();
        for(String key: keys){
            System.out.println(key);
        }
    }
}

Solution 14 - Java

What I'll do which is very simple but waste memory is to map the values with a key and do the oposite to map the keys with a value making this:

private Map<Object, Object> team1 = new HashMap<Object, Object>();

it's important that you use <Object, Object> so you can map keys:Value and Value:Keys like this

team1.put("United", 5);

team1.put(5, "United");

So if you use team1.get("United") = 5 and team1.get(5) = "United"

But if you use some specific method on one of the objects in the pairs I'll be better if you make another map:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

private Map<Integer, String> team1Keys = new HashMap<Integer, String>();

and then

team1.put("United", 5);

team1Keys.put(5, "United");

and remember, keep it simple ;)

Solution 15 - Java

To get Key and its value

e.g

private Map<String, Integer> team1 = new HashMap<String, Integer>();
  team1.put("United", 5);
  team1.put("Barcelona", 6);
    for (String key:team1.keySet()){
                     System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
                }

Will print: Key: United Value:5 Key: Barcelona Value:6

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmasbView Question on Stackoverflow
Solution 1 - JavaMatteoView Answer on Stackoverflow
Solution 2 - Javajames.garrissView Answer on Stackoverflow
Solution 3 - JavaFabio FilippiView Answer on Stackoverflow
Solution 4 - JavaÓscar LópezView Answer on Stackoverflow
Solution 5 - JavaEmperorView Answer on Stackoverflow
Solution 6 - JavaMateusz ChromińskiView Answer on Stackoverflow
Solution 7 - JavasachinView Answer on Stackoverflow
Solution 8 - JavasakirowView Answer on Stackoverflow
Solution 9 - JavatzgView Answer on Stackoverflow
Solution 10 - Javaghanshyam singhView Answer on Stackoverflow
Solution 11 - JavaOriciView Answer on Stackoverflow
Solution 12 - Javaraman rayatView Answer on Stackoverflow
Solution 13 - JavaAbdul RizwanView Answer on Stackoverflow
Solution 14 - Javauser3763927View Answer on Stackoverflow
Solution 15 - JavaEmmanuel RView Answer on Stackoverflow