[java] Get keys from HashMap in Java

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

This question is related to java data-structures java-6

The answer is


Use functional operation for faster iteration.

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


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.


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.


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


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


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

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

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

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


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

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") );

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]


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to data-structures

Program to find largest and second largest number in array golang why don't we have a set datastructure How to initialize a vector with fixed length in R C compiling - "undefined reference to"? List of all unique characters in a string? Binary Search Tree - Java Implementation How to clone object in C++ ? Or Is there another solution? How to check queue length in Python Difference between "Complete binary tree", "strict binary tree","full binary Tree"? Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Examples related to java-6

How to use TLS 1.2 in Java 6 How to set specific Java version to Maven Which JDK version (Language Level) is required for Android Studio? Get java.nio.file.Path object from java.io.File Get keys from HashMap in Java How to convert java.lang.Object to ArrayList? Using File.listFiles with FileNameExtensionFilter Is it possible to read the value of a annotation in java? Dealing with "java.lang.OutOfMemoryError: PermGen space" error