DEV Community

Neelakandan R
Neelakandan R

Posted on • Edited on

Map Interface

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()); } } } 
Enter fullscreen mode Exit fullscreen mode

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.

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<Integer, String> 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 (Entry entry : studentMap.entrySet()) { System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue()); } } } 
Enter fullscreen mode Exit fullscreen mode

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<Integer, String> 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<Integer, String> entry : studentMap.entrySet()) { System.out.println("ID: " + entry.getKey() + ", Name: " + entry.getValue()); } } } 
Enter fullscreen mode Exit fullscreen mode

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()); } } } 
Enter fullscreen mode Exit fullscreen mode

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 } } } } 
Enter fullscreen mode Exit fullscreen mode

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<Integer> 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); } } 
Enter fullscreen mode Exit fullscreen mode

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<String, Integer> hm = new HashMap<String, Integer>(); hm.put("Idli", 20); // Entry=key+value hm.put("Dosai", 30);// all Entry=set hm.put("Pongal", 40);// Entry System.out.println(hm); } } 
Enter fullscreen mode Exit fullscreen mode

output
Pongal=40, Dosai=30, Idli=20}

Map mock question

package Afternoon; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class col_map { private String name = "neelakandan"; private int age = 39; public static void main(String[] args) { Map m = new LinkedHashMap(); m.put("name", "neelakandan");// key no dubiplicate//value may have dublictae m.put("age", "39"); // m.put("name","neel"); // m.put("age","3"); // m.put("name","nee"); // m.put("age","9"); Set s = m.entrySet();//Set of entriesSet of entries Iterator it = s.iterator(); while (it.hasNext()) { Entry entry = (Entry) it.next(); System.out.println(entry.getKey() + " " + entry.getValue()); } } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)