Java Hashmap: How to get key from value?

To get the key for a given value in a java.util.HashMap, you can use the entrySet() method of the java.util.HashMap class to get a set of the mappings in the map, and then iterate over the set and check the value of each mapping.

Here is an example of how you can get the key for a given value in a java.util.HashMap:

import java.util.HashMap;
import java.util.Map;

public class HashMapKeyFromValueExample {
  public static void main(String[] args) {
    HashMap<Integer, String> map = new HashMap<>();
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
    map.put(4, "D");

    String value = "B";
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
      if (value.equals(entry.getValue())) {
        System.out.println("Key: " + entry.getKey());
        break;
      }
    }
  }
}

This example creates a java.util.HashMap that maps integers to strings, and then iterates over the mappings in the map, checking the value of each mapping. If the value is equal to the string "B", the key for that mapping is printed. In this case, the output would be "Key: 2", because the value "B" is mapped to the key 2 in the map.

Note that this approach will only find the first key that is mapped to the given value. If there are multiple keys that map to the same value, you will need to use a different approach to get all of the keys.

For example, you could use a java.util.List to store the keys, and add all of the keys that map to the given value to the list. Here is an example of how you could do this:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HashMapKeyFromValueExample {
  public static void main(String[] args) {
    HashMap<Integer, String> map = new HashMap<>();
    map.put(1, "A");
    map.put(2, "B");
    map.put(3, "C");
    map.put(4, "D");
    map.put(5, "B");

    String value = "B";
    List<Integer> keys = new ArrayList<>();
    for (Map.Entry<Integer, String> entry : map.entrySet()) {
      if (value.equals(entry.getValue())) {
        keys.add(entry.getKey());
      }
    }
    System.out.println("Keys: " + keys);
  }
}

This example will find all of the keys that map to the value "B" in the map, and store them in a list. The output will be "Keys: [2, 5]", because the keys 2 and 5 both map to the value "B" in the map.