In Java, java.util.Map
is an interface that represents a collection of key-value pairs. It’s part of the Java Collections Framework and provides methods to manipulate and access elements based on their keys.
he java.util.Map
interface in Java provides several methods to work with key-value pairs. Here are some of the important methods defined by the Map
interface:
In Java, the Map
interface is implemented by several classes that provide different functionalities and characteristics. Here are some of the common child classes that implement the Map
interface in Java
Difference between HashMap, TreeMap and Hashtable
HashMap | TreeMap | Hashtable | |
Iteration order | Random | Sorted | Random |
Null keys/values | allowed | not allowed | not allowed |
Synchronised | not synchronized | not synchronized | synchronized |
Interfaces | Map | Map | Map |
HashMap
Map map=new HashMap<>();
map.put(1, "A");
map.put("A", 1);
System.out.println(map); //{1=A, A=1}
Map<Integer,String> map2=new HashMap<>();
map2.put(1, "A");
map2.put(1, "B");
System.out.println(map2); //{1=B}
Map<Integer,String> map3=new HashMap<>();
map3.putAll(map);
System.out.println(map3); //{1=A, A=1}
System.out.println(map3.size()); //2
System.out.println(map3.isEmpty()); //false
System.out.println(map3.containsKey(2)); //false
System.out.println(map3.containsValue(2)); //false
System.out.println(map3.get(2)); //null
TreeMap
// Creating a TreeMap
TreeMap<String, Integer> map = new TreeMap<>();
// Adding key-value pairs to the TreeMap
map.put("Apple", 10);
map.put("Banana", 20);
map.put("Orange", 15);
map.put("Mango", 25);
// Printing the TreeMap
System.out.println("TreeMap: " + map);
// Iterating over the TreeMap
System.out.println("Iterating over TreeMap:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// Accessing specific values
System.out.println("Value for 'Banana': " + map.get("Banana"));
// Checking for a specific key
if (map.containsKey("Apple")) {
System.out.println("TreeMap contains key 'Apple'");
}
// Removing a key-value pair
map.remove("Orange");
System.out.println("After removing 'Orange': " + map);
// Checking for a specific value
if (map.containsValue(25)) {
System.out.println("TreeMap contains value 25");
}
// Getting the first and last keys
System.out.println("First key: " + map.firstKey());
System.out.println("Last key: " + map.lastKey());
// Getting a view of the keys
System.out.println("Key set: " + map.keySet());
Appreciation to my father who told me regarding this website, this web site is actually remarkable.