GroTechMinds

GroTechMinds logo
java map collection tutorial and examples

Java Map Collection Tutorial

Map stores the value in the form of key and value pair. A map cannot contain duplicate keys, Each key is associated with a single value.

Example:

  1. Mapping of Students name with their RollNo
  2. Mapping of Airport Nae with their Airport Code
  3. Mapping of Employee Name with their EmployeeId

Collection Framework:

  • It is the set of Predefined classes & interfaces which is used to store multiple data.
  • It contains 2 main parts(Packages):-
  1.  java.util.Collection;
  2. java.util.Map;

Map Hierarchy in Java:

java map

Collection Hierarchy in Java:

java map 1

As a part of this blog we will keep our discussion only for Map Interface.

Below are the useful methods of MAP Interface:

Method Description
put(Object, Object) Adds a new key: value pair to the map
putAll(Map) Copies all the mappings of the specified map into the new map
size() Returns the total number of key: value pairs in a map
clear() Clears and removes all the mappings
equals(Object) Checks the equality between two maps
containsKey(Object) Returns a boolean value depending on whether the specified key is mapped or not
containsValue(Object) Returns a boolean value depending on whether the specified value is mapped or not
get(Object) Returns the value mapped with the specified key or null if the key is not mapped
isEmpty() Checks whether the map is empty
keySet() Returns a set view of the mapped keys
remove(Object) Removes an element’s key mapping
value() Creates a collection of the values of a map
putIfAbsent(Object key,Object value) If the specified key is not already associated with a value (or is mapped to null) associates it with the given value and returns null, else returns the current value.
replace(Object Key,Object Oldvalue,Object NewValue) Replaces the entry for the specified key only if currently mapped to the specified value
replace(Object key,Object value) Replaces the entry for the specified key only if it is currently mapped to some value.
1. Lets understand how to use put(Object,Object) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;

public class Map_Interface 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	//Upcasting HashMap to Map Interface
	m1.put("student 1", "Manish");
	//Adds a new key: value pair to the map
	m1.put("student 2", "Abhishek");
	m1.put("student 3", "Sunita");
	m1.put("student 4", "Jeetu");
	System.out.println(m1);
}
}

				
			

Output:

{student 3=Sunita, student 4=Jeetu, student 1=Manish, student 2=Abhishek}

Screenshot:

map 2
2. Lets understand how to use putAll(Collection) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface2 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("student 1", "Manish");
	m1.put("student 2", "Abhishek");
	m1.put("student 3", "Sunita");
	m1.put("student 4", "Jeetu");
	System.out.println(m1);
	Map m2=new HashMap();
	//Copies all the mappings of the m1map into the new map m2
	m2.putAll(m1);
	m2.put("Student 5", "Reeyansh");
	System.out.println(m2);

}	
}

				
			

Output:

{student 3=Sunita, student 4=Jeetu, student 1=Manish, student 2=Abhishek}
{student 3=Sunita, student 4=Jeetu, Student 5=Reeyansh, student 1=Manish, student 2=Abhishek}

Screenshot:

map 3
3. Lets understand how to use clear() in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface3 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("student 1", "Manish");
	m1.put("student 2", "Abhishek");
	m1.put("student 3", "Sunita");
	m1.put("student 4", "Jeetu");
	System.out.println(m1);
	m1.clear();
	//Clears and removes all the mappings
	System.out.println(m1);
}
}

				
			

Output:

{student 3=Sunita, student 4=Jeetu, student 1=Manish, student 2=Abhishek}
{}

Screenshot:

map 4
4. Lets understand how to use Equals in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface4 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("student 1", "Manish");
	m1.put("student 2", "Abhishek");
	m1.put("student 3", "Sunita");
	m1.put("student 4", "Jeetu");
	System.out.println(m1);
	Map m2=new HashMap();
	m2.put("student 1", "Manish");
	m2.put("student 2", "Abhishek");
	m2.put("student 3", "Sunita");
	m2.put("student 4", "Jeetu");
	System.out.println(m2);
	boolean a1=	m1.equals(m2);
	//Checks the equality between two maps
	System.out.println(a1);
}
}

				
			

Output:

{student 3=Sunita, student 4=Jeetu, student 1=Manish, student 2=Abhishek}
{student 3=Sunita, student 4=Jeetu, student 1=Manish, student 2=Abhishek}
true

Screenshot:

map 5
5. Lets understand how to use get(Object) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface5 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	System.out.println(m1.get("Sugar"));
	//Returns the value mapped with the specified key or null if the key is not mapped
	
}
}
				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
2

Screenshot:

map 6
6. Lets understand how to use remove(Object) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface6
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	Map m2=new HashMap();
	m2.putAll(m1);
	System.out.println(m2);
	m2.put("Oil", 5);
	System.out.println("After Removing:");
	m2.remove("Rice");
	//Removes an element’s key mapping
	System.out.println(m2);
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
{Jaggery=3, Cereals=25, Sugar=2, Rice=10}
After Removing:
{Jaggery=3, Cereals=25, Oil=5, Sugar=2}

Screenshot:

map 7
7. Lets understand how to use replace(Object,Value) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface7 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	m1.replace("Rice", 90);
	/Replaces the entry for the specified key only if it is currently mapped to some value.
	System.out.println(m1);	
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
{Cereals=25, Jaggery=3, Sugar=2, Rice=90}

Screenshot:

map 8
8. Lets understand how to use size() in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface8 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	System.out.println(m1.size());	
	//Returns the total number of key: value pairs in a map
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
4

Screenshot:

map 9
9. Lets understand how to use containsKey(Object key) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface89 
{
public static void main(String[] args) {
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	System.out.println(m1.containsKey("Rice"));
	//Returns a boolean value depending on whether the specified key is mapped or not
}
}
				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
true

Screenshot:

map 10
10. Lets understand how to use containsValue(Object value) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface10 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);
//Returns a boolean value depending on whether the specified value is mapped or not	
	System.out.println(m1.containsValue(2));
	
}
}
				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
true

Screenshot:

map 11
11. Lets understand how to use replace(Object key,Object oldvalue,Object newvalue) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface11 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	m1.replace("Sugar", 2, 20);
	//Replaces the entry for the specified key only if currently mapped to the specified value
	System.out.println(m1);
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
{Cereals=25, Jaggery=3, Sugar=20, Rice=10}

Screenshot:

map 12
12. Lets understand how to use values() in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface112 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	System.out.println(m1.values());
	//Creates a collection of the values of a map
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
[25, 3, 2, 10]

Screenshot:

map 13
13. Lets understand how to use keySet() in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface13 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);	
	System.out.println(m1.keySet());
	//Returns a set view of the mapped keys
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
[25, 3, 2, 10]

Screenshot:

map 14
14. Lets understand how to use putIfAbsent(Object key,Object value) in Map Interface.
				
					package ab43;
import java.util.HashMap;
import java.util.Map;
public class Map_Interface14 
{
public static void main(String[] args) 
{
	Map m1=new HashMap();
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	System.out.println(m1);
	m1.putIfAbsent("Wheat", 100);
	//If the specified key is not already associated with a value associates it with the given value 
	System.out.println(m1);
}
}

				
			

Output:

{Cereals=25, Jaggery=3, Sugar=2, Rice=10}
{Cereals=25, Jaggery=3, Wheat=100, Sugar=2, Rice=10}

Screenshot:

Example 1: Just because the “Wheat” key was not present it got added in m1.

map 15

Example 2: Just because the “Rice” key was already present it did not get added in m1.

map 16
15. How to fetch the value of MAP Interface:

Case 1: Using EntrySet to fetch both key and value

				
					package ab43;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class Map_Interface17 
{
public static void main(String[] args) 
{
	Map<String,String> m1=new HashMap<String,String>();
	//Upcasting from HashMap to Map Interface
	m1.put("INR","Indian Rupee");
	m1.put("USD","US Dollars");
	m1.put("CAD", "Canadian Dollars");
	m1.put("GBP","United Kingdom Pound");
	//let's use for each loop to fetch key and value
	
	//fetching both key and value using entryset method
	for(Map.Entry<String,String> value1: m1.entrySet())
	{
		System.out.println(value1);
	}	
}
}
				
			

Output:

GBP=United Kingdom Pound
USD=US Dollars
CAD=Canadian Dollars
INR=Indian Rupee

Screenshot:

map 17

Case 2: Using keySet() to fetch only keys and using values() to fetch only values

				
					package ab43;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class Map_Interface16 
{
public static void main(String[] args) {
	Map<String,Integer> m1=new HashMap<String,Integer>();
	//Upcasting from HashMap to Map Interface
	m1.put("Rice",10);
	m1.put("Sugar",2);
	m1.put("Jaggery", 3);
	m1.put("Cereals",25);
	//lets use for each loop to fetch key separately and value separately
	for(String key: m1.keySet())
	{
		System.out.println("Keys-> "+key);
	}
	for(Integer value: m1.values())
	{
		System.out.println("Values-> "+value);
	}
	//fetching both key and value using entryset method
	for(Entry<String, Integer> value1: m1.entrySet())
	{
		System.out.println("Key and Value -> "+value1);
	}
}
}

				
			

Output:

Keys-> Cereals
Keys-> Jaggery
Keys-> Sugar
Keys-> Rice
Values-> 25
Values-> 3
Values-> 2
Values-> 10
Key and Value -> Cereals=25
Key and Value -> Jaggery=3
Key and Value -> Sugar=2
Key and Value -> Rice=10

Screenshot:

map 18

Case 3: Using Iterator to fetch both key and value together.

				
					package ab43;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Map_Interface18 
{
public static void main(String[] args) 
{
	Map<String,String> m1=new HashMap<String,String>();
	//Upcasting from HashMap to Map Interface
	m1.put("INR","Indian Rupee");
	m1.put("USD","US Dollars");
	m1.put("CAD", "Canadian Dollars");
	m1.put("GBP","United Kingdom Pound");	
	Iterator<Entry<String, String>> i1=m1.entrySet().iterator();
	
	while(i1.hasNext())
	{
	System.out.println(i1.next());
	}	
}
}

				
			

Output:

GBP=United Kingdom Pound

USD=US Dollars

CAD=Canadian Dollars

INR=Indian Rupee

Screenshot:

map 19

Now let’s discuss how List Set and Map Interface are different from each other:

List Set Map
Package java.util.List java.util.Set java.util.Map
Duplicate List allows you to store duplicate elements in java. Set does not allow storing duplicate elements in java. Map stores data in the form of key-value pairs; it does not allow to store duplicate keys but allows duplicate values in java.
Insertion Order Maintain Insertion order Does not maintain Insertion Order Most of the Map classes do not maintain insertion order.
Null List allows you to store many null keys in java. Most of the Set implementations allow to add only one null in java HashMap allows one null key and many null values.
TreeMap doesn’t allow null keys but allows many null values.
LinkedHashMap allows one null key and many null values.
Classes List implementation classes are Array List, LinkedList. Set implementation classes are HashSet, LinkedHashSet, and TreeSet. Map implementation classes are HashMap, HashTable, TreeMap, WeakHashMap, and LinkedHashMap.
When to use If you need to access the elements frequently by using the index then we can use the list If you want to create a collection of unique elements then we can use set If you want to store the data in the form of a key/value pair then we can use the map.
Traversing We can traverse using Iterator and ListIterator We can traverse using Iterator It can’t be traverse but you can fetch using keyset(),value() and entrySet()
Popular Courses
Share:
Upskill Yourself
Consult Us