Search code examples
javahashmap

Java HashMap key value storage and retrieval


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?


Solution

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