Map In Java

Map In Java :

  • java.util.Map interface represents a mapping between a key and a value.
  • Is not a subtype of the Collection interface.
  • Map contain unique keys and each key can map to at most one value.
  • A Map does not allow duplicate keys, but you can have duplicate values. HashMap and LinkedHashMap allow null keys and values, but TreeMap doesn’t allow any null key or value.
  • key-value association mapping called the dictionaries.
  • Each key and value pair is known as an entry.
  • A Map can not be traversed. so you need to convert it into Set using keySet() or entrySet() method.

1) HashMap: No order maintain. only one null key. HashMap is not thread-safe. HashMap implements Cloneable and Serializable interfaces. Unordered collection. Map map = new HashMap();
2) LinkedHashMap: It inherits HashMap class. It maintains insertion order. Implementation of Map.
3) TreeMap: Implementation of Map and SortedMap. It maintains ascending order. Map map = new TreeMap();

Map In Java

constructor
HashMap()
HashMap(Map< ? extends k, ? extends V> m)
HashMap(int capacity)
HashMap(int capacity, float fillratio)

method
1) size(): returns number of entries

import java.util.*;

class Student {

    public static void main(String args[]) {
        Map<Integer, String> map = new HashMap<Integer, String>();
        map.put(100, "Kamlesh");
        map.put(101, "Vijay");
        map.put(102, "Ankit");

        for (Map.Entry m : map.entrySet()) {
            System.out.println(m.getKey() + " " + m.getValue());
        }

        //comparingByKey()
        System.out.println("\ncomparingByKey");
        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .forEach(System.out::println);

        //comparingByKey() in descending order
        System.out.println("\ncomparingByKey() in descending order");
        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
                .forEach(System.out::println);

        //comparingByValue
        System.out.println("\ncomparingByValue");
        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue())
                .forEach(System.out::println);

        //comparingByValue() in descending order
        System.out.println("\ncomparingByValue() in descending order");
        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
                .forEach(System.out::println);
    }
}

output :

100 Kamlesh
101 Vijay
102 Ankit

comparingByKey
100=Kamlesh
101=Vijay
102=Ankit

comparingByKey() in descending order
102=Ankit
101=Vijay
100=Kamlesh

comparingByValue
102=Ankit
100=Kamlesh
101=Vijay

comparingByValue() in descending order
101=Vijay
100=Kamlesh
102=Ankit

Iterating Over a Map :

import java.util.*;

class CountryCode{

    public static void main(String args[]) {
        Map<String, String> mapCountryCodes = new HashMap<>();

        mapCountryCodes.put("1", "USA");
        mapCountryCodes.put("44", "United Kingdom");
        mapCountryCodes.put("33", "France");
        mapCountryCodes.put("81", "Japan");

        Set<String> setCodes = mapCountryCodes.keySet();
        Iterator<String> iterator = setCodes.iterator();

        while (iterator.hasNext()) {
            String code = iterator.next();
            String country = mapCountryCodes.get(code);

            System.out.println(code + " => " + country);
        }

        System.out.println("\nGet value");
        Collection<String> countries = mapCountryCodes.values();

        for (String country : countries) {
            System.out.println(country);
        }

        //entrySet
        System.out.println("\nentrySet");
        Set<Map.Entry<String, String>> entries = mapCountryCodes.entrySet();

        for (Map.Entry<String, String> entry : entries) {
            String code = entry.getKey();
            String country = entry.getValue();

            System.out.println(code + " => " + country);
        }

        System.out.println("\nLambda foreach");
        mapCountryCodes.forEach((code, country) -> System.out.println(code + " => " + country));
    }
}


output :

44 => United Kingdom
33 => France
1 => USA
81 => Japan

Get value
United Kingdom
France
USA
Japan

entrySet
44 => United Kingdom
33 => France
1 => USA
81 => Japan

Lambda foreach
44 => United Kingdom
33 => France
1 => USA
81 => Japan

Concurrent Maps :

Map<Integer, String> map = Collections.synchronizedMap(new HashMap<>());

Set<Integer> keySet = map.keySet();
 
synchronized (map) {
    Iterator<Integer> iterator = keySet.iterator();
 
    while (iterator.hasNext()) {
        Integer key = iterator.next();
        String value = map.get(key);
    }
}

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapExample {

    public static void main(String[] args) {

        Map<String, String> data = new HashMap<>();

        data.put("A", "A"); // put example
        data.put("B", "B");
        data.put("C", "C");
        data.put("D", null); // null value
        data.put(null, "Z"); // null key

        String value = data.get("C"); // get example
        System.out.println("Key = C, Value = " + value);

        value = data.getOrDefault("E", "Default Value");
        System.out.println("Key = E, Value=" + value);

        boolean keyExists = data.containsKey(null);
        boolean valueExists = data.containsValue("Z");

        System.out.println("keyExists= " + keyExists + ", valueExists= " + valueExists);

        Set<Entry<String, String>> entrySet = data.entrySet();
        System.out.println(entrySet);

        System.out.println("data map size=" + data.size());

        Map<String, String> data1 = new HashMap<>();
        data1.putAll(data);
        System.out.println("data1 mappings= " + data1);

        String nullKeyValue = data1.remove(null);
        System.out.println("data1 null key value = " + nullKeyValue);
        System.out.println("data1 after removing null key = " + data1);

        Set<String> keySet = data.keySet();
        System.out.println("data map keys = " + keySet);

        Collection<String> values = data.values();
        System.out.println("data map values = " + values);

        data.clear();
        System.out.println("data map is empty =" + data.isEmpty());

    }

}