可能重复:
Java Hashmap:如何从值中获取键?
我知道 HashMap 包含一个特定的整数变量作为值。如何获取与此值关联的键?
此代码将执行此操作:
public List<Object> getKeysFromValue(Map<?, ?> hm, Object value){
List <Object>list = new ArrayList<Object>();
for(Object o:hm.keySet()){
if(hm.get(o).equals(value)) {
list.add(o);
}
}
return list;
}
干得好:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test
{
public static void main( String args[] )
{
Map < Integer , Integer > map = new HashMap < Integer , Integer >();
map.put( 1 , 2 );
map.put( 3 , 4 );
map.put( 5 , 6 );
map.put( 7 , 4 );
List< Integer > keys = new ArrayList< Integer >();
Integer value = 4;
for ( Integer key : map.keySet() )
{
if ( map.get( key ).equals( value ) )
{
keys.add( key );
}
}
System.out.println( value + " has been found in the following keys: " + keys );
}
}
输出是:
4 has been found in the following keys: [7, 3]
Set<Map.Entry> entries = hashMap.entrySet();
for(Map.Entry entry : entries) {
if(entry.getValue().equals(givenValue)) {
return entry.getKey();
}
}
如果您知道键,哈希图可以帮助您找到值。如果您真的想从值中获取键,则必须遍历所有项目,比较值,然后获取键。
遍历 entrySet 更快,因为您不会为每个键查询两次映射。
public Set<Object> getKeysFromValue(Map<Object, Integer> map, int value) {
Set<Object> keys = new HashSet<Object>();
for (Map.Entry<Object, Integer> entry:map.entrySet()) {
//if value != null
if (entry.getValue() == value) {
keys.add(entry.getKey());
}
}
return keys;
试试这个......简短而甜蜜的方式......
HashMap<String, Integer> list = new HashMap<String,Integer>();
for (Map.Entry<String, Integer> arr : list.entrySet()){
System.out.println(arr.getKey()+" "+arr.getValue());
}