Map Interface
The map interface in Java is a structure that holds a set of key-value pairs where each key is unique and points to one value only. It is a component of the java.util package and is being widely used in Java programming to structure and get data in an ordered manner. A Map is useful if you have to search, update or delete elements on the basis of a key.
Class------------Description
HashMap----------HashMap is the implementation of Map, but it doesn't maintain any order.
LinkedHashMap-----LinkedHashMap is the implementation of Map. It inherits HashMap class. It maintains insertion order.
TreeMap-----------TreeMap is the implementation of Map and SortedMap. It maintains ascending order.
Useful methods of Map interface
V put(Object key, Object value)--It is used to insert an entry in the map.
void putAll(Map map)---It is used to insert the specified map in the map.
V putIfAbsent(K key, V value)---It inserts the specified value with the specified key in the map only if it is not already specified.
V remove(Object key)---It is used to delete an entry for the specified key.
boolean remove(Object key, Object value)---It removes the specified values with the associated specified keys from the map.
Set keySet()---It returns the Set view containing all the keys.
boolean containsValue(Object value)---This method returns true if some value equal to the value exists within the map, else return false.
boolean containsKey(Object key)---his method returns true if some key equal to the key exists within the map, else return false.
boolean equals(Object o)---It is used to compare the specified Object with the Map.
V get(Object key)---This method returns the object that contains the value associated with the key.
boolean isEmpty()---This method returns true if the map is empty; returns false if it contains at least one key.
**
V replace(K key, V value)**--It replaces the specified value for a specified key.
int size()---This method returns the number of entries in the map.
Map.Entry Interface
Map.Entry is an inner interface of the Map interface which represents a single pair of key-value in a map. It additionally allows one to get a map and to iterate over its entries, convert the map to a set of keys/values, etc. It returns a collection-view of the map, whose elements are of this class. It provides methods to get keys and values.
K getKey()---It is used to obtain a key.
V getValue()---It is used to obtain value.
int hashCode()---It is used to obtain hashCode.
**
V setValue(V value)**---It is used to replace the value corresponding to this entry with the specified value.
boolean equals(Object o)---It is used to compare the specified object with the other existing objects.
import java.util.*;
public class MapExample1 {
public static void main(String[] args) {
Map map=new HashMap();
//Adding elements to map
map.put(1,"Amit");
map.put(5,"Rahul");
map.put(2,"Jai");
map.put(6,"Amit");
//Traversing Map
Set set=map.entrySet();//Converting to Set so that we can traverse
Iterator itr=set.iterator();
while(itr.hasNext()){
//Converting to Map.Entry so that we can get key and value separately
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
}
}
Output:
1 Amit
2 Jai
5 Rahul
6 Amit
HashMap
HashMap is an important data structure in Java which implements the Map interface. In this way, it provides a scheme for storing of key-value pairs. A HashMap has each key unique and only has one value for each key. This enables the lookup of values by their keys that are paired with them.
Example:
HashMapExample.java
import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap to store student IDs and their corresponding names
Map studentMap = new HashMap<>();
// Adding some student records to the HashMap
studentMap.put(1001, "John Smith");
studentMap.put(1002, "Emily Brown");
studentMap.put(1003, "Michael Johnson");
// Retrieving and printing a student's name based on their ID
int studentIdToFind = 1002;
String studentName = studentMap.get(studentIdToFind);
if (studentName != null) {
System.out.println("Student with ID " + studentIdToFind + " is: " + studentName);
} else {
System.out.println("Student with ID " + studentIdToFind + " not found.");
}
// Iterating over the entries of the HashMap and printing each key-value pair
System.out.println("Student Records:");
for (Map.Entry entry : studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
// Checking if a student ID exists in the HashMap
int idToCheck = 1004;
boolean exists = studentMap.containsKey(idToCheck);
System.out.println("Student with ID " + idToCheck + " exists in records: " + exists);
}
}
Output:
Student with ID 1002 is: Emily BrownStudent Records:
ID: 1001, Name: John Smith
ID: 1002, Name: Emily Brown
ID: 1003, Name: Michael Johnson
Student with ID 1004 exists in records: false
LinkedHashMap
LinkedHashMap is a class in Java that extends HashMap and implements the Map interface. It resembles Hashmap in functionality but maintains a predictable iteration order, that is, the order in which keys were inserted into the map (insertion-order). This in turn makes LinkedHashMap a good candidate for cases when the order of insertion needs to be preserved.
LinkedHashMapExample.java
import java.util.LinkedHashMap;
import java.util.Map;
public class LinkedHashMapExample {
public static void main(String[] args) {
// Creating a LinkedHashMap to store student IDs and their corresponding names
Map studentMap = new LinkedHashMap<>();
// Adding some student records to the LinkedHashMap
studentMap.put(1001, "John Smith");
studentMap.put(1002, "Emily Brown");
studentMap.put(1003, "Michael Johnson");
// Iterating over the entries of the LinkedHashMap and printing each key-value pair
System.out.println("Student Records:");
for (Map.Entry entry : studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Output:
Student Records:
ID: 1001, Name: John Smith
ID: 1002, Name: Emily Brown
ID: 1003, Name: Michael Johnson
TreeHashMap
TreeMap in Java is a sorted map implementation that stores key-value pairing in a Red-Black tree structure. It guarantees that the elements are arranged in relation to their keys, either naturally or by a user-defined comparator.
Example:
TreeMapExample.java
import java.util.*;
public class TreeMapExample {
public static void main(String[] args) {
// Creating a TreeMap to store student IDs and their corresponding names
TreeMap studentMap = new TreeMap<>();
// Adding some student records to the TreeMap
studentMap.put(1003, "Michael Johnson");
studentMap.put(1001, "John Smith");
studentMap.put(1002, "Emily Brown");
// Iterating over the entries of the TreeMap and printing each key-value pair
System.out.println("Student Records:");
for (Map.Entry entry : studentMap.entrySet()) {
System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue());
}
}
}
Output:
Student Records:
ID: 1001, Name: John Smith
ID: 1002, Name: Emily Brown
ID: 1003, Name: Michael Johnson
program:
package collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class collec_hashmap {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("Idli", 20); // Entry=key+value
hm.put("Dosai", 30);// all Entry=set
hm.put("Pongal", 40);// Entry
// all key=set
// all value=collection
//
// System.out.println(hm.get("Idli"));//20
Set s = hm.entrySet();
System.out.println(s);// [Pongal=40, Dosai=30, Idli=20]
Set ss = hm.entrySet();
Iterator it = ss.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
Output:
[Pongal=40, Dosai=30, Idli=20]
Pongal=40
Dosai=30
Idli=20
package collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class collec_hashmap {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("Idli", 20); // Entry=key+value
hm.put("Dosai", 30);// all Entry=set
hm.put("Pongal", 40);// Entry
// all key=set
// all value=collection
//
// System.out.println(hm.get("Idli"));//20
Set s = hm.entrySet();
System.out.println(s);// [Pongal=40, Dosai=30, Idli=20]
Set ss = hm.entrySet();
Iterator it = ss.iterator();
while (it.hasNext()) {
Entry entry = (Entry) it.next();// both value and key
Object ab = entry.getValue();
// separate only value
int price = (int) ab;// object to int
if (price == 20) {
System.out.println(entry.getKey());// separate//output--idli
// System.out.println(it.next());//entry
}
Object ac = entry.getKey();
String menu = (String) ac;
if (menu.equals("Idli")) {
System.out.println(entry.getValue());// output--20
}
}
}
}
Output:
[Pongal=40, Dosai=30, Idli=20]
Idli
20
Add arraylist
package collections;
import java.util.ArrayList;
import java.util.Iterator;
public class arraylist_add {
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(30);
al.add(20);
al.add(40);
//al.add("hi");
int total = 0;
Iterator it = al.iterator();
while (it.hasNext()) {
total = total + (int) it.next();
}
System.out.println(total);
}
}
Output:
90
Add map
package collections;
import java.util.HashMap;
import java.util.Iterator;
public class hashmap_add {
public static void main(String[] args) {
HashMap hm = new HashMap();
hm.put("Idli", 20); // Entry=key+value
hm.put("Dosai", 30);// all Entry=set
hm.put("Pongal", 40);// Entry
System.out.println(hm);
}
}
output
Pongal=40, Dosai=30, Idli=20}