Java HashMap 键值存储与检索

Java HashMap key value storage and retrieval(Java HashMap 键值存储与检索)

本文介绍了Java HashMap 键值存储与检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储值并从 Java HashMap 中检索它们.

I want to store values and retrieve them from a Java HashMap.

这是我目前所拥有的:

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");
}

我想从 HashMap 中检索所有键和值作为 Java 集合或实用程序集(例如 LinkedList).

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 键值示例:

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 键值存储与检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java HashMap 键值存储与检索

基础教程推荐