Organizational Research By

Surprising Reserch Topic

How to get key depending upon the value from hashmap java collection?

want to retrieve the specific key associated with the value in a hashmap

I want to retrieve the key of "ME", how can I get it?

Code snippet :

HashMap map = new HashMap();

asked Jun 19, 2015 in Core java by rajesh
0 votes

Related Hot Questions

1 Answer

0 votes
There's a small problem with what you are trying to do. There can be multiple occurrences of the same value in a hashmap, so if you look up the key by value, there might be multiple results (multiple keys with the same value).

Nevertheless, if you are sure this won't occur, it can be done; see the following example:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        HashMap map = new HashMap();
        map.put(5, "vijf");
        map.put(36, "zesendertig");
    static Integer getKey(HashMap map, String value) {
        Integer key = null;
        for(Map.Entry entry : map.entrySet()) {
            if((value == null && entry.getValue() == null) || (value != null && value.equals(entry.getValue()))) {
                key = entry.getKey();
        return key;
answered Jun 19, 2015 by rajesh