代码如下:
/**
* 根据value获取所有key
*/
private static Set<String> getKeys(Map<String,String> map, String value){
Set<String> keySet = new HashSet<>();
// 遍历map
for (Map.Entry<String, String> entry : map.entrySet()) {
// 如果value和key对应的value相同
if(value.equals(entry.getValue())){
keySet.add(entry.getKey());
}
}
return keySet;
}
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value1");
map.put("key4", "value2");
map.put("key5", "value2");
map.put("key6", "value3");
// 获取所有value2的key值
Set<String> keySet = getKeys(map, "value2");
for (String key : keySet) {
System.out.println(key);
}
}
测试运行