Java Collections - HashMap Cheat-Sheet

import java.util.HashMap;

public class HashMapDemo {
    public static void main(String[] args) {
        //create a HashMap
        HashMap map = new HashMap();
        map.put(1, "One");
        map.put(2, "Two");        
        map.put(5, "Five");
        map.put(3, "Three");

        System.out.println(map);
        //String as key
        HashMap map2 = new HashMap();
        map2.put("One", 1);
        map2.put("Two", 2);
        map2.put("Five", 5);
        map2.put("Three", 3);
        System.out.println(map2);
        //get value by key
        System.out.println("Value for key 2:"+map.get(2));
        System.out.println("Value for key Two:"+map2.get("Two"));
        System.out.println("Containes key 2:"+map.containsKey(2));

        //add another map
        HashMap map3 = new HashMap();
        map3.put(4, "Four");
        map3.put(6, "Six");
        map3.put(7, "Seven");
        map.putAll(map3);

        System.out.println(map);
        //remove an element
        map.remove(2);
        System.out.println(map);
        //replace element
        map.put(3, "@Three@");
        System.out.println(map);
        //get the length of the map
        System.out.println("Length of Map:"+map.size());

        //iterate using foreach loop
        System.out.println("Iterating using foreach loop:");
        map.forEach((k,v)->System.out.println("Key:"+k+" Value:"+v));

        //using keySet
        System.out.println("Iterating using keySet:");
        for (Integer key : map.keySet()) {
            System.out.println("Key:"+key+" Value:"+map.get(key));
        }
        //using entrySet
        System.out.println("Iterating using entrySet:");
        for (HashMap.Entry entry : map.entrySet()) {
            System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue());
        }
        //using entrySet with forEach
        System.out.println("Iterating using entrySet with forEach:");
        map.entrySet().forEach((entry)->System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue()));
        //using entrySet with forEach and lambda
        System.out.println("Iterating using entrySet with forEach and lambda:");
        map.entrySet().forEach((entry)->{
            System.out.println("Key:"+entry.getKey()+" Value:"+entry.getValue());
        });
        //using values
        System.out.println("Iterating using values:");
        for (String value : map.values()) {
            System.out.println("Value:"+value);
        }
        //

        
    }
}

Post a Comment

Previous Post Next Post