我在Java中有一个这样的Hashmap:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我像这样填充它:
team1.put("United", 5);
我怎么才能拿到钥匙?类似于:team1.getKey()返回“United”。
我在Java中有一个这样的Hashmap:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我像这样填充它:
team1.put("United", 5);
我怎么才能拿到钥匙?类似于:team1.getKey()返回“United”。
当前回答
我要做的非常简单,但浪费内存的是将值映射到一个键,并相反地将键映射到一个值,这样做:
private Map<Object, Object> team1 = new HashMap<Object, Object>();
使用<Object, Object>很重要,这样你就可以像这样映射key:Value和Value: key
team1。(“联合”,5);
team1。把(5,“联合”);
如果你使用team1。get("United") = 5和team1。get(5) = "United"
但如果你对其中一个对象使用特定的方法,我会更好,如果你做另一张地图:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
private Map<Integer, String> team1Keys = new HashMap<Integer, String>();
然后
team1。(“联合”,5);
team1Keys。把(5,“联合”);
记住,保持简单。
其他回答
试试这个简单的程序:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}
public class MyHashMapKeys {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println(key);
}
}
}
如果你只是需要一些简单的验证。
public String getKey(String key)
{
if(map.containsKey(key)
{
return key;
}
return null;
}
然后你可以搜索任何键。
System.out.println( "Does this key exist? : " + getKey("United") );
当你想要获得参数(United)的值(5),你也可以考虑使用双向映射(例如,由Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html提供)。
获取Key及其值
e.g
private Map<String, Integer> team1 = new HashMap<String, Integer>();
team1.put("United", 5);
team1.put("Barcelona", 6);
for (String key:team1.keySet()){
System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
}
将打印:键:联合值:5 值:6