有什么方法可以获取与 map 中已知值关联的键吗?通常你知道键,你想得到值,但我想做相反的事情,从值到键。是否可以?
最佳答案
是的,您必须遍历映射中的值,然后将每个键存储在列表中:
for (Map.Entry<K,V> entry : map.entrySet()) {
V value = entry.getValue();
if (value.equals(someTargetValue) {
// add key (entry.getKey()) to list
}
}
或者您可以使用 bidirectional map , 但请注意:
This map enforces the restriction that there is a 1:1 relation between keys and values, meaning that multiple keys cannot map to the same value.
关于Java 映射,从值到键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5670395/