java HashMap通过value反查key的代码示例

时间:2021-07-06 11:00:07

代码如下:


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


结果如下:

复制代码代码如下:


1
2
3
4
5