简体   繁体   English

Java HashMap 键值存储和检索

[英]Java HashMap key value storage and retrieval

I want to store values and retrieve them from a Java HashMap.我想存储值并从 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 ).我想从 HashMap 中检索所有键和值作为 Java 集合或实用程序集(例如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?有没有办法将键值作为列表检索?

I use these three ways to iterate a map. 我使用这三种方法来迭代地图。 All methods ( keySet , values , entrySet ) return a collection. 所有方法( 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());

Since Java 8 i often use Stream s with lambda expressions . 由于Java 8我经常使用带有lambda表达式的 Stream

    // 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()));

Java Hashmap key value example: 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.
}

map.keySet()会给你所有的键

//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);

    }

}

You can use keySet() to retrieve the keys. 您可以使用keySet()来检索密钥。 You should also consider adding typing in your Map, eg : 您还应该考虑在地图中添加输入,例如:

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();
public static void main(String[] args) {

    HashMap<String, String> hashmap = new HashMap<String, String>();

    hashmap.put("one", "1");
    hashmap.put("two", "2");
    hashmap.put("three", "3");
    hashmap.put("four", "4");
    hashmap.put("five", "5");
    hashmap.put("six", "6");

    Iterator<String> keyIterator = hashmap.keySet().iterator();
    Iterator<String> valueIterator = hashmap.values().iterator();

    while (keyIterator.hasNext()) {
        System.out.println("key: " + keyIterator.next());
    }

    while (valueIterator.hasNext()) {
        System.out.println("value: " + valueIterator.next());
    }
}
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));
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM