Java HashMap键值存储和检索 [英] Java HashMap key value storage and retrieval
本文介绍了Java HashMap键值存储和检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我到目前为止:
$ b $我想存储值并从Java HashMap中检索它们。 b
public void processHashMap()
{
HashMap hm = new HashMap();
hm.put(1,godric gryfindor);
hm.put(2,helga hufflepuff);
hm.put(3,rowena ravenclaw);
hm.put(4,salazaar slytherin);
$ / code>
我想从HashMap中检索所有键和值作为Java集合或实用程序集(例如 LinkedList
)。
我知道如果我知道密钥,这个:
hm.get(1);
有没有办法将键值检索为列表?
< Java HashMap键值示例:
<$ c 解决方案
$ c $ public void processHashMap(){
//将keys-> value对添加到散列表:
HashMap hm = new HashMap();
hm.put(1,godric gryfindor);
hm.put(2,helga hufflepuff);
hm.put(3,rowena ravenclaw);
hm.put(4,salazaar slytherin);
//然后获取数据:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet()。iterator();
while(itr.hasNext()){
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //键列表将被打印。
}
//将keys-> value对添加到散列表:
HashMap hm = new HashMap();
hm.put(1,godric gryfindor);
hm.put(2,helga hufflepuff);
hm.put(3,rowena ravenclaw);
hm.put(4,salazaar slytherin);
//然后获取数据:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet()。iterator();
while(itr.hasNext()){
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //键列表将被打印。
}
I want to store values and retrieve them from a Java HashMap.
This is what I have so far:
public void processHashMap()
{
HashMap hm = new HashMap();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
}
I want to retrieve all Keys and Values from the HashMap as a Java Collection or utility set (for example LinkedList
).
I know I can get the value if I know the key, like this:
hm.get(1);
Is there a way to retrieve key values as a list?
解决方案
Java Hashmap key value example:
public void processHashMap() {
//add keys->value pairs to a hashmap:
HashMap hm = new HashMap();
hm.put(1, "godric gryfindor");
hm.put(2, "helga hufflepuff");
hm.put(3, "rowena ravenclaw");
hm.put(4, "salazaar slytherin");
//Then get data back out of it:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet().iterator();
while(itr.hasNext()) {
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //The key list will be printed.
}
这篇关于Java HashMap键值存储和检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文