问题描述
我是Java新手。我实现了一个哈希表,如下所示。
在特定场景中,我想使用密钥的值检索密钥。
例如:如果用户输入Dravid,那么我需要从哈希映射中检索2。
我只想使用一个哈希地图来实现这一点。
任何人都可以帮我解决这个问题吗?
的HashMap<字符串,字符串> streetno = new HashMap< String,String>();
streetno.put(1,Sachin);
streetno.put(2,Dravid);
streetno.put(3,Sehwag);
streetno.put(4,Laxman);
streetno.put(5,Kohli);
要做到这一点,您需要使用bi - 双向散列表。考虑使用。
如果没有它,您需要迭代映射中的所有键/值对,并测试值等于Dravid时的值,然后返回键。像这样:
for(Entry< String,String> pair:streetno.entrySet()){
if pair.getValue()。equals(Dravid)){
System.out.println(在键处找到Dravid:+ pair.getKey());
}
}
I'm new to Java. I implemented a Hash Map as shown below.In a particular scenario I wanted to retrieve the key using values of the key.For Eg: If user enters "Dravid", then I need to retrieve "2" from the Hash Map.
And I want to use only one hash map to implement this.
Can anyone help me with this?
HashMap<String,String> streetno=new HashMap<String,String>();
streetno.put("1", "Sachin");
streetno.put("2", "Dravid");
streetno.put("3","Sehwag");
streetno.put("4", "Laxman");
streetno.put("5", "Kohli");
To do this, you would need to use a bi-directional hashmap. Consider using the Apache Commons implementation.
Without it, you'd need to iterate over all the key / value pairs in the map and test for when the value equals "Dravid", then return the key. Like so:
for (Entry<String, String> pair : streetno.entrySet()) {
if (pair.getValue().equals("Dravid")) {
System.out.println("Found Dravid at key: " + pair.getKey());
}
}
这篇关于从哈希映射中检索密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!