1. 程式人生 > >HashMap根據value獲取key值

HashMap根據value獲取key值

font 重復 span new 新建 cit public entry static

public static String getCityId(HashMap<String,String> citys, String city){
Set set = citys.entrySet();//新建一個不可重復的集合
ArrayList<String> arr = new ArrayList<String>();//新建一個集合
Iterator it = set.iterator();//遍歷的類
while(it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();//找到所有key-value對集合
if(entry.getValue().equals(city)) {//通過判斷是否有該value
String s = (String) entry.getKey();//取得key
arr.add(s);
}
}
return arr.get(0);
}

HashMap根據value獲取key值