Java HashMap键值存储和检索

20

我想要将值存储到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)。

我知道如果我知道键,可以获取对应的值,例如:

hm.get(1);
有没有一种方法可以将键值以列表的形式检索出来?

1
你考虑过查阅Javadoc文档吗? - user207421
6个回答

37
我使用以下三种方法来迭代Map。所有方法(keySetvaluesentrySet)都返回一个集合。
// Given the following map
Map<KeyClass, ValueClass> myMap;

// Iterate all keys
for (KeyClass key  : myMap.keySet()) 
    System.out.println(key);

// Iterate all values
for (ValueClass value  : myMap.values()) 
    System.out.println(value);

// Iterate all key/value pairs
for (Entry<KeyClass, ValueClass> entry  : myMap.entrySet()) 
    System.out.println(entry.getKey() + " - " + entry.getValue());

自从Java 8之后,我经常使用Streamlambda表达式

    // Iterate all keys
    myMap.keySet().stream().forEach(key -> System.out.println(key));

    // Iterate all values
    myMap.values().parallelStream().forEach(value -> System.out.println(value));

    // Iterate all key/value pairs
    myMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));

15

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.
}

10

1
谢谢你的回复,兄弟......那么我能把返回值强制转换成LinkedList吗? - Arjun K P
返回值是 Set 类型之一,因此不能直接使用,但可以从中构建。 - jmj

3
//import statements
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;

// hashmap test class
public class HashMapTest {

    public static void main(String args[]) {

        HashMap<Integer,String> hashMap = new HashMap<Integer,String>(); 

        hashMap.put(91, "India");
        hashMap.put(34, "Spain");
        hashMap.put(63, "Philippines");
        hashMap.put(41, "Switzerland");

        // sorting elements
        System.out.println("Unsorted HashMap: " + hashMap);
        TreeMap<Integer,String> sortedHashMap = new TreeMap<Integer,String>(hashMap);
        System.out.println("Sorted HashMap: " + sortedHashMap);

        // hashmap empty check
        boolean isHashMapEmpty = hashMap.isEmpty();
        System.out.println("HashMap Empty: " + isHashMapEmpty);

        // hashmap size
        System.out.println("HashMap Size: " + hashMap.size());

        // hashmap iteration and printing
        Iterator<Integer> keyIterator = hashMap.keySet().iterator();
        while(keyIterator.hasNext()) {
            Integer key = keyIterator.next();
            System.out.println("Code=" + key + "  Country=" + hashMap.get(key));
        }

        // searching element by key and value
        System.out.println("Does HashMap contains 91 as key: " + hashMap.containsKey(91));
        System.out.println("Does HashMap contains India as value: " + hashMap.containsValue("India"));

        // deleting element by key
        Integer key = 91;
        Object value = hashMap.remove(key);
        System.out.println("Following item is removed from HashMap: " + value);

    }

}

HashMap基本操作的完整示例 - user3339147

1

您可以使用keySet()来检索键。您还应该考虑在Map中添加类型,例如:

Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff"); 
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");

Set<Integer> keys = hm.keySet();

0
void hashMapExample(){

    HashMap<String, String> hMap = new HashMap<String, String>();
    hMap.put("key1", "val1");
    hMap.put("key2", "val2");
    hMap.put("key3", "val3");
    hMap.put("key4", "val4");
    hMap.put("key5", "val5");

    if(hMap != null && !hMap.isEmpty()){
        for(String key : hMap.keySet()){
            System.out.println(key+":"+hMap.get(key));
        }
    }
}

请访问此网址:http://stackoverflow.com/help,它将有助于提高您的内容质量。 - Willie Cheng

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接