Map in the Java

Map is an interface in the Java Collection Framework that maps unique keys to values. In simple terms, it is a collection of key-value pairs. In this blog, we will discuss the features and examples of the Map interface in Java.

Features of Map

  1. A Map does not allow duplicate keys. Each key can map to at most one value.

  2. A Map is not ordered. The order in which the elements are stored is undefined.

  3. Map is implemented by several classes, including HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap, etc.

  4. Map provides methods to add, remove, and retrieve key-value pairs.

  5. Map does not allow null keys (in some implementations) but allows null values.

  6. Map is not synchronized and is not thread-safe.

Examples of Map

Example 1: Creating a HashMap and adding key-value pairs.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 100);
map.put("banana", 50);
map.put("orange", 75);
System.out.println(map);

Output:

{apple=100, banana=50, orange=75}

Example 2: Removing a key-value pair from a HashMap.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 100);
map.put("banana", 50);
map.put("orange", 75);
System.out.println(map);
map.remove("banana");
System.out.println(map);

Output:

{apple=100, banana=50, orange=75}
{apple=100, orange=75}

Example 3: Retrieving the value of a key from a HashMap.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 100);
map.put("banana", 50);
map.put("orange", 75);
System.out.println(map.get("apple"));
System.out.println(map.get("mango"));

Output:

100
null

Example 4: Iterating over a HashMap.

Map<String, Integer> map = new HashMap<>();
map.put("apple", 100);
map.put("banana", 50);
map.put("orange", 75);
for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey() + " -> " + entry.getValue());
}

Output:

apple -> 100
banana -> 50
orange -> 75

In conclusion, Map is a powerful interface in the Java Collection Framework that provides a way to store key-value pairs. It is implemented by several classes and provides methods to add, remove, and retrieve key-value pairs. It is efficient, easy to use, and provides constant-time performance for many operations.