Java HashMap key value storage and retrieval

101,723

Solution 1

I use these three ways to iterate a map. All methods (keySet, values, entrySet) return a collection.

// 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 Streams with lambda expressions.

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

Solution 2

map.keySet() would give you all the keys

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

    }

}

Solution 4

You can use keySet() to retrieve the keys. You should also consider adding typing in your Map, e.g :

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

Solution 5

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());
    }
}
Share:
101,723
Arjun K P
Author by

Arjun K P

Musicophile, Ambivert, Fitness Freak, Cosmic Explorer

Updated on July 09, 2022

Comments

  • Arjun K P
    Arjun K P almost 2 years

    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?

  • Arjun K P
    Arjun K P about 12 years
    thanks for ur reply bro.....so is it possible for me to typecast the return value into a LinkedList........??
  • user3339147
    user3339147 over 10 years
    A complete example on basic operations of HashMap
  • Willie Cheng
    Willie Cheng about 8 years
    please follow this URL it will be useful to lift your content quality up
  • jmj
    jmj over 6 years
    returned value is one of the type of Set, so not directly but you can construct from it