Get keys from HashMap in Java

Get keys from HashMap in Java

One of most likely situation we seek is get keys of values from HashMap. While iterating through HashMap, there might be different scenarios as how mapping of key to value is done. 

We’ll discuss and see how we can get key/s of value/s of below mentioned pattern-

  1. Key to Value: Many to One (Many keys with same value)
  2. Key to Value: One to One (Every Key has unique value)

Lets see an example demonstrating both scenarios

package code2succeed.com.getkeys;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class GetKeys {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void main(String[] args) {
		HashMap<String, String> hm = new HashMap<String, String>();
		hm.put("Key1", "Value1");
		hm.put("Key2", "Value2");
		hm.put("Key3", "Value2");
		hm.put("Key4", "Value2");
		hm.put("Key5", "Value3");
		hm.put("Key6", "Value4");
		System.out.println("Key Value pair stored in HashMap are: ");
		System.out.println(hm+"\n");
		
	//In case of multiple values i.e. many to one mapping	
		//Value for which Key is to be searched
		String valueforkeysearch = "Value2";	
		// Set where unique key will be stored
		HashSet keyforvalue = new HashSet();	 	
		Set entryset = hm.entrySet();
		Iterator itr = entryset.iterator();		
		while(itr.hasNext()){
			Map.Entry me = (Entry) itr.next();
			if(me.getValue().equals(valueforkeysearch)){
				keyforvalue.add(me.getKey());
			}		
		}
		//Print all the key corresponding to value
		System.out.println("Keys corrosponding to "+valueforkeysearch+" are "+keyforvalue);	
		
	//In case of multiple values i.e. one to one mapping	
		//Value for which Key is to be searched
		String uniquevalueforKeysearch = "Value3";			
		Set uniqueentryset = hm.entrySet();
		Iterator uniqueitr = uniqueentryset.iterator();		
		while(uniqueitr.hasNext()){
			Map.Entry uniqueme = (Entry) uniqueitr.next();
			if(uniqueme.getValue().equals(uniquevalueforKeysearch)){
				//Print key corresponding to value
				System.out.println("Key corrosponding to "+uniquevalueforKeysearch+" is "+uniqueme.getKey());	
			}		
		}	
	}
}

Output:

Key Value pair stored in HashMap are: 
{Key2=Value2, Key1=Value1, Key6=Value4, Key5=Value3, Key4=Value2, Key3=Value2}

Keys corrosponding to Value2 are [Key2, Key4, Key3]
Key corrosponding to Value3 is Key5

Stay tuned for more updates!

Leave a Reply

Your email address will not be published. Required fields are marked *