A code example of a Java HashMap looking up the key by value

  • 2020-04-01 02:26:32
  • OfStack


import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapValueGetKey {
  public static void main(String[] args) {
    Map map = new HashMap<>();
    map.put(1,"A");
    map.put(2,"A");
    map.put(3,"A");
    map.put(4,"A");
    map.put(5,"A");

    String value = "A";
    ArrayList arr = valueGetKey(map, value);
    if(!arr.isEmpty()) {
      for(int i=0; i<arr.size(); i++) {
        System.out.println(arr.get(i));
      }
    }

  }
  private static ArrayList valueGetKey(Map map,String value) {
    Set set = map.entrySet();
    ArrayList arr = new ArrayList<>();
    Iterator it = set.iterator();
    while(it.hasNext()) {
      Map.Entry entry = (Map.Entry)it.next();
      if(entry.getValue().equals(value)) {
        int s = (int)entry.getKey();
        arr.add(s);
      }
    }
    return arr;
  }
}

The results are as follows:

1
2
3
4
5

Related articles: