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:
- Stores Key and Value:
key -> value
Example:
1 -> Apple
2 -> Mango
3 -> Banana
- Key Must Be Unique
Duplicate key not allowed.
Example:
map.put(1,"Arul");
map.put(1,"Raj");
1 = Raj //key and values are replaced.
- Values Can Duplicate:
1 = Arul
2 = Arul
Allowed.
- One Null Key (depends on class)
In HashMap, one null key allowed.
Example:
null = Test
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);
}
}
Classes that Implement Map
- HashMap:
- Fast
- No order guarantee
- LinkedHashMap:
- Maintains insertion order
- TreeMap:
- Sorted by key
Top comments (0)