DEV Community

Cover image for Understanding the Map Interface in Java
Arul .A
Arul .A

Posted on

Understanding the Map Interface in Java

Map:

  • Map is an interface in Java used to store data in key-value pairs.

  • It is part of Java Collections Framework, but technically Map does not extend Collection.

  • Map is an interface in Java used to store data in the form of:

key -> value

Each key points to one value.

Example:

101 -> Arul
102 -> Raj
103 -> Vijay

Here:

101, 102, 103 are keys
Arul, Raj, Vijay are values

Main Features of Map:

  1. Stores Key and Value:

key -> value

Example:

1 -> Apple
2 -> Mango
3 -> Banana
Enter fullscreen mode Exit fullscreen mode
  1. Key Must Be Unique

Duplicate key not allowed.
Example:

map.put(1,"Arul");
map.put(1,"Raj");

1 = Raj  //key and values are replaced.

Enter fullscreen mode Exit fullscreen mode
  1. Values Can Duplicate:

1 = Arul
2 = Arul

Allowed.

  1. One Null Key (depends on class)

In HashMap, one null key allowed.

Example:

null = Test
Enter fullscreen mode Exit fullscreen mode

Methods in map:

Method - Use

put(k,v) - Add data
get(k) - Get value by key
remove(k) - Delete by key
containsKey(k) - Check key
containsValue(v - Check value
size() - Number of pairs
clear() - Remove all
keySet() - Get all keys
values() - Get all values
entrySet() - Get key-value pairs

Example:

import java.util.*;

public class Main {
    public static void main(String[] args) {

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

        map.put(101,"Arul");
        map.put(102,"Raj");
        map.put(103,"Vijay");

        System.out.println(map);

        System.out.println(map.get(102));

        map.remove(101);

        System.out.println(map);
    }
}
Enter fullscreen mode Exit fullscreen mode

Classes that Implement Map

  1. HashMap:
  • Fast
  • No order guarantee
  1. LinkedHashMap:
  • Maintains insertion order
  1. TreeMap:
  • Sorted by key

Top comments (0)