Java Map Interface Tutorial With Implementation & Examples

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This Comprehensive Java Map Tutorial Covers how to Create, Initialize, and Iterate through Maps. You will also learn about Map Methods and Implementation Examples:

You will get to know the basics of map interface, methods supported by map interface, and other specific terms related to map interface.

Maps collection in Java is a collection that maps a key to a value. It is a collection consisting of keys and values. Each entry in the map consists of a key with its corresponding value. The keys are unique in maps. Maps can be used typically when we need to modify a collection based on a key value.

=> Check ALL Java Tutorials Here.

Map Interface in Java

Maps In Java

The map in Java is a part of the java.util.map interface. The map interface is not a part of the collection interface and that is the reason for which maps are different from the other collections.

The general hierarchy of the map interface is shown below.

general hierarchy of the map interface

As shown above there are two interfaces to implement map i.e. map interface and sortedMap interface. There are three classes namely i.e. HashMap, TreeMap, and LinkedHashMap.

These map types are described below:

ClassDescription
LinkedHashMapExtends from HashMap class. This map maintains the insertion order
HashMapImplement a map interface. No order is maintained by HashMap.
TreeMapImplements both map and sortedMap interface. TreeMap maintains an ascending order.

Points To Remember About Maps.

  1. In maps, each key can map to the at most one value. Also, there cannot be duplicate keys in maps.
  2. Map implementations like HashMap and LinkedHashMap allow null key and null values. However, TreeMap does not allow it.
  3. A map cannot be traversed as it is. Hence for traversing, it needs to be converted to set using keyset () or entrySet () method.

Create A Map In Java

To create a map in Java, first, we have to include the interface in our program. We can use one of the following statements in the program to import the map functionality.

import java.util.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;

We need to instantiate a concrete implementation of the map as it is an interface.

The following statements create a map in Java.

Map hash_map = new HashMap();
Map tree_map = new TreeMap();

The above statements will create maps with default specifications.
We can also create generic maps specifying the types for both key and value.

Map<String, Object> myMap = new HashMap<String, Object>();

The above definition will have keys of type string and objects as values.

Initialize A Map In Java

It can be initialized using the following methods:

#1) Using Collections

Java Collections class has factory methods that can be used to initialize collections including maps.

Some methods used to initialize map are as follows:

(1) Collections.EmptyMap()

The Collections.EmptyMap () returns a serializable and immutable map that is empty. For example, the following line of code,

Map<String, String> myMap = Collections.EMPTY_MAP;

This will create an empty map. The above method may throw ‘unchecked assignment warning’ and thus we can also use the type-safe form as follows.

Map<String, String> myMap = Collections.emptyMap ();

(2) Collections.unModifiableMap()

The method unModifiableMap () takes another map as an argument and creates an unmodifiable view of the original map.

Map<String, String> myMap = Collections.EMPTY_MAP;
Map<String, String> map_unmodifiable = Collections.unmodifiableMap (myMap);

(3) Collections.singletonMap()

Collections class also provides a factory method ‘singletonMap()’ that creates an immutable singleton map having only one entry.

Map<String, String> singleton_map = Collections.singletonMap("CHN", "Beijing");

#2) Using Java 8

We can obtain a stream of data from Java 8 stream API methods and construct maps using Collectors.

Some of the methods to construct maps are:

(1) Collectors.toMap()

We collect a stream and then use Collectors.toMap () method to construct a map.

Map<String, String> map = Stream.of(new String[][]{{"USA", "Washington"},
{"United Kingdom", "London"}
 }).collect(Collectors.toMap(p -> p[0], p -> p[1]));

The above statement creates a map from the Java 8 stream.

(2) Collectors.collectingAndThen()

In this, we adapt the toMap () method that allows the collector to produce an immutable map using the collectingAndThen () method.

Map<String, String> immutableMap = Stream.of(new String[][]{
{"USA", "Washington"}, {"United Kingdom", "London”}
}).collect(Collectors.collectingAndThen(Collectors.toMap(p -> p [0], p -> p[1]),
Collections::<String, String>unmodifiableMap));

#3) Using the put method of the Map Interface

The put () method of the map interface can be used to assign initial values to maps.

#4) Using Double Brace Initialization

The technique “double brace initialization” creates an inner class. This class is anonymous and has an instance initializer in it. This is not a preferred technique and should be avoided as it may result in memory leaks or serialization problems.

The below program shows the various methods of initializing a map discussed above.

import java.util.*; 
import java.util.stream.*; 
import java.util.stream.Collectors;  
public class Main { 
    public static void main(String args[])  { 
        //using Collections
        //create an empty map
        Map<String, String> emptymap = Collections.EMPTY_MAP;
        //create unmodifiable map using Collections
        Map<String, String> unmodifiableMap = Collections.unmodifiableMap(emptymap);
        System.out.println("unmodifiableMap map values:" + unmodifiableMap);
        //singleton map
        Map<Integer, String> singleton_map = Collections.singletonMap(10, " TEN");
        System.out.println("\n\nsingleton_map Map values:" + singleton_map);
        //using Java 8
        //1. toMap method of collectors class
        Map<String, String> map_cities = Stream.of(new String[][]{
			{"MH", "Mumbai"}, {"CH", "Chennai"}, {"DL", "New Delhi"}
						}).collect(Collectors.toMap(p -> p[0], p -> p[1]));
		System.out.println("\n\nmap_cities values: " + map_cities);				
		//2. collectingAndThen method
		Map<String, String> capitals_Map = Stream.of(new String[][]{
			{"MAH", "Mumbai"}, {"GOA", "Panaji"}, 	{"KAR", "Bangaluru"}
                        }).collect(Collectors.collectingAndThen
                        (Collectors.toMap(p -> p[0], p -> p[1]),
					Collections::<String, String>unmodifiableMap));

  
        System.out.println("\n\ncapitals_Map values: " + capitals_Map);
       
        //double brace initialization
        Map<String, String> country_map = new HashMap<String, String>();
        country_map.put("USA", "Washington");
        country_map.put("UK", "London");
        country_map.put("IND", "Delhi");
        country_map.put("GER", "Berlin");
        System.out.println("\n\nMap values:" + country_map);
    } 
}

Output:

unmodifiableMap map values:{}
singleton_map Map values:{10= TEN}
map_cities values: {CH=Chennai, DL=New Delhi, MH=Mumbai}
capitals_Map values: {MAH=Mumbai, GOA=Panaji, KAR=Bangaluru}
Map values:{USA=Washington, GER=Berlin, UK=London, IND=Delhi}

initializing a map

Iterate Over Map In Java And Print The Map

We can traverse the map just in the same way in which we traverse the other collections. In addition to traversing map entries, we can also traverse only the keys or only the values in the map. Note that to traverse a map, it needs to be converted to set first.

The following methods are used to traverse the map entries.

Using Entry Iterator

In this method, we obtain an entry iterator from an entry set. Then using the getKey and getValue methods, we retrieve the key-value pair for each map entry.

The following program shows the usage of an entry iterator.

import java.util.*; 
import java.util.stream.*; 
import java.util.stream.Collectors;  
public class Main { 
    public static void main(String args[]) { 
        //use toMap method of collectors class to populate the map
        Map<String, String> map_cities = Stream.of(new String[][]{
								{"MH", "Mumbai"},
								{"CH", "Chennai"},
								{"DL", "New Delhi"}
						}).collect(Collectors.toMap(p -> p[0], p -> p[1]));
        //transform map to set
        Set<Map.Entry<String, String>> entries = map_cities.entrySet();
        //declare an iterator
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        System.out.println("The map entries are:");
        System.out.println("        KEY     VALUE");
        //iterate and print key and value pairs.
        while(iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            System.out.println("\t" + entry.getKey() + "\t" +entry.getValue());
        }
    } 
}

Output:

The map entries are:
KEY VALUE
CH Chennai
DL New Delhi
MH Mumbai

Using entry iterator

In the above program, we obtain an entry iterator from the map using the entrySet method. Then we traverse the map using the hasNext () method of entry iterator and print the key-value pair.

Using An Entry for-each Loop

Here we traverse the entrySet using for-each loop and the implementation is shown below.

import java.util.*; 
import java.util.stream.*; 
import java.util.stream.Collectors;  
public class Main { 
    public static void main(String args[]) 
    { 
        //use toMap method of collectors class to populate the map
        Map<String, String> map_cities = Stream.of(new String[][]{
					{"MH", "Mumbai"},
					{"CH", "Chennai"},
					{"DL", "New Delhi"}
					}).collect(Collectors.toMap(p -> p[0], p -> p[1]));
        System.out.println("The map entries are:");
        System.out.println("        KEY     VALUE");
        //iterate using for each over entry set and print key and value pairs.
        for(Map.Entry<String, String> entry : map_cities.entrySet()){
            System.out.println("\t" + entry.getKey() + "\t" +entry.getValue());
        }
    } 
}

Output:

The map entries are:
KEY VALUE
CH Chennai
DL New Delhi
MH Mumbai

Using an entry for-each loop

Map Methods

Map interface in Java supports various operations similar to those supported by other collections. In this section, we will discuss the various methods provided by Map API in Java. As the scope of this tutorial is limited to introducing a map interface in general, we will not describe these methods.

We will discuss these methods in detail while discussing map interface classes.

The following table lists all the methods provided by map API.

Method NameMethod PrototypeDescription
getV get(Object key) Returns the object or value for the given key
putV put(Object key, Object value) Insert key-value entry in the map
putAllvoid putAll(Map map) Insert given map entries in the map. In other words copies or clones a map.
keySetSet keySet() Returns set view of the map.
entrySetSet< Map.Entry< K,V >> entrySet() Returns set the view for a given map
valuesCollection values() Returns collection view of the values in the map.
removeV remove(Object key)Delete a map entry for the given key
sizeint size() Returns number of entries in the map
clearvoid clear() Clears the map
isEmptyboolean isEmpty() Checks if the map is empty and returns true if yes.
containsValueboolean containsValue(Object value)Returns true if the map contains the value equal to the given value
containsKeyboolean containsKey(Object key)Returns true if a given key exists in the map
equalsboolean equals(Object o) Compares specified object o with the map
hashCodeint hashCode()
returns the hash code for the Map
forEachvoid forEach(BiConsumer< ? super K,? super V > action) Performs given action for each entry in the map
getOrDefaultV getOrDefault(Object key, V defaultValue) Returns specified value for the given key or its default value if the key is not present
removeboolean remove(Object key, Object value) Removes specified keys and values
replaceV replace(K key, V value)Replaces the given key with the specified value
replaceboolean replace(K key, V oldValue, V newValue)Replaces the old value with a new value for a given key
replaceAllvoid replaceAll(BiFunction < ? super K,? super V,? extends V > function) Invokes given function to replace all the map entries
putIfAbsentV putIfAbsent(K key, V value) Inserts the given key, value only if it is not already present
computeV compute(K key, BiFunction < ? super K,? super V,? extends V > remappingFunction) Computes mapping for specified key and value given the mapping function.
computeIfAbsentV computeIfAbsent(K key, Function < ? super K,? extends V > mappingFunction)Compute the value for the given key using the mapping function if not already present.
computeIfPresentV computeIfPresent(K key, BiFunction < ? super K,? super V,? extends V > remappingFunction) Computes new mapping for the given key with the given remapping function if the key value is already present
mergeV merge(K key, V value, BiFunction < ? super V,? super V,? extends V > remappingFunction) Associates a given key with the value if it is not already associated or is associated with the null value.

All the above methods are supported by the map interface. Note that the methods that appear shaded are the new methods that were included in Java 8.

Java Map Implementation

The following program implements a map example in Java. Here we use most of the methods discussed above.

The example demonstrates various get operations, put, and set operations.

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

public class Main {
	public static void main(String[] args) {
        	//create a map
	Map<String, String> country_map = new HashMap<>();
        	//assign values to the map
	country_map.put("IND", "India"); 
	country_map.put("SL", "Srilanka");
	country_map.put("CHN", "China");
	country_map.put("KOR", "Korea"); 
	country_map.put(null, "Z"); // null key
	country_map.put("XX", null); // null value

	String value = country_map.get("CHN"); // get 
	System.out.println("Key = CHN, Value : " + value);

	value = country_map.getOrDefault("XX", "Default Value"); //getOrDefault
	System.out.println("\nKey = XX, Value : " + value);

	boolean keyExists = country_map.containsKey(null);     //containsKey
	boolean valueExists = country_map.containsValue("Z");  //containsValue

	System.out.println("\nnull keyExists : " + keyExists + ", null valueExists= " + valueExists);

	Set<Entry<String, String>> entrySet = country_map.entrySet();  //entrySet
	System.out.println("\nentry set for the country_map: " + entrySet);

	System.out.println("\nSize of country_map : " + country_map.size());  //size

	Map<String, String> data_map = new HashMap<>();
	data_map.putAll(country_map);       //putAll
	System.out.println("\ndata_map mapped to country_map : " + data_map);

	String nullKeyValue = data_map.remove(null);  //remove
	System.out.println("\nnull key value for data_map : " + nullKeyValue);
	System.out.println("\ndata_map after removing null key = " + data_map);

	Set<String> keySet = country_map.keySet();      //keySet
 	System.out.println("\ndata map keys : " + keySet);

		Collection<String> values = country_map.values();   //values
		System.out.println("\ndata map values : " + values);

		country_map.clear();        //clear
		System.out.println("\ndata map after clear operation, is empty :" + country_map.isEmpty());
	}
}

Output:

Key = CHN, Value : China
Key = XX, Value : null
null keyExists : true, null valueExists= true
entry set for the country_map: [null=Z, XX=null, CHN=China, SL=Srilanka, IND=India, KOR=Korea]
Size of country_map : 6
data_map mapped to country_map : {null=Z, XX=null, CHN=China, SL=Srilanka, IND=India, KOR=Kore
a}
null key value for data_map : Z
data_map after removing null key = {XX=null, CHN=China, SL=Srilanka, IND=India, KOR=Korea}
data map keys : [null, XX, CHN, SL, IND, KOR]
data map values : [Z, null, China, Srilanka, India, Korea]
data map after clear operation, is empty :true

get operations, put and set operations

Sorting A Map In Java

As a map consists of key-value pairs, we can sort the map on keys or values.

In this section, we will sort a map on both keys and values.

Sort By Key

To sort a map on keys, we can use a treemap. The treemap sorts the keys automatically. The below Java program converts a map into a treemap and displays the sorted keys.

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        //declare and initialize a map
        Map<String, String> country_map = new HashMap<String, String>();
        country_map.put("I", "India");
        country_map.put("C", "China");
        country_map.put("A", "America");
        country_map.put("D", "Denmark");
        country_map.put("X", "Hongkong");
        //print original map
        System.out.println("Original Unsorted Map: ");
        display_map(country_map);

        System.out.println("\nMap sorted by Key: ");
        //convert map to treemap and display it in which keys are auto sorted
        Map<String, String> treecountry = new TreeMap<String, String>(country_map);
        display_map(treecountry);

    }

    public static <K, V> void display_map(Map<K, V> map) {
       //obtain entry iterator and display key value pairs of map
        for (Map.Entry<K, V> entry : map.entrySet()) {
            System.out.println("\t" + entry.getKey() + "\t\t" + entry.getValue());
        }
    }

}

Output:

Original Unsorted Map:
A America
C China
D Denmark
X Hongkong
I India
Map sorted by Key:
A America
C China
D Denmark
I India
X Hongkong

Sort by key

The above program creates a map of <String, String> consisting of a single alphabet code as keys and country names as values. First, we display the original map which is not sorted. Then we convert the map into a treemap that automatically sorts the keys. Finally, we display the sorted treemap on keys.

Sort By Value

To sort a map based on values, we first convert the map into a list. Then we sort this list using Collections.sort () method that uses a comparator to compare the values and arrange them in a specific order.

Once the list is sorted, the linked list entries are again copied to map which gives us the sorted map.

The following Java program demonstrates the sorting of a map based on value. The program uses LinkedHashMap which is passed on to sorting function. In the sorting function, it is converted to a linked list and sorted. After sorting it is converted back to LinkedHashMap.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        //define and initialize a map
        LinkedHashMap<String, String> capitals_map = new LinkedHashMap<>();
        capitals_map.put("NEP", "Kathmandu");
        capitals_map.put("IND", "New Delhi");
        capitals_map.put("USA", "Washington");
        capitals_map.put("UK", "London");
        capitals_map.put("AUS", "Canberra");
        //print original map
        System.out.println("Original unsorted map: ");
        System.out.println(capitals_map);
        //call sortMap method 
        Map<String, String> sorted_Map = sortMap(capitals_map);
        //print the sorted map
        System.out.println("\nMap sorted on value : ");
        System.out.println("\tKey\tValue ");
        for (Map.Entry<String, String> entry : sorted_Map.entrySet())
        {
            System.out.println("\t" + entry.getKey()+ "\t" + entry.getValue());
        }
    }
public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> linked_map) {
        //create a linkedlist from LinkedHashMap
        List<Map.Entry<String, String>> capital_List = 
        new LinkedList<>(linked_map.entrySet());
        //sort the LinkedList
        Collections.sort(capital_List, (o1, o2) -> 
        o1.getValue().compareTo(o2.getValue()));
        //Create LinkedHashMap from linkedlist and return it
        LinkedHashMap<String, String> finalMap = new LinkedHashMap<>();
        for (Map.Entry<String, String> entry : capital_List)
        {
            finalMap.put(entry.getKey(), entry.getValue());
        }

        return finalMap;
    }
}

Output:

Original unsorted map:
{NEP=Kathmandu, IND=New Delhi, USA=Washington, UK=London, AUS=Canberra

Map sorted on value :
Key Value
AUS Canberra
NEP Kathmandu
UK London
IND New Delhi
USA Washington

Sort by value

Concurrent Map In Java

A concurrentMap is an interface that inherits from java.util.map interface. The concurrentMap interface was first introduced in JDK 1.5 and provides a map that handles concurrent access.

The concurrentMap interface is part of java.util.concurrent package.

The following Java program demonstrates the concurrentMap in Java.

import java.util.concurrent.*; 
class Main { 
    public static void main(String[] args) { 
        //create and initialize concurrentHashMap
        ConcurrentHashMap m = new ConcurrentHashMap(); 
        m.put(100, "Red"); 
        m.put(101, "Green"); 
        m.put(102, "Blue"); 
        System.out.println("\nInitial Concurrent Map : " + m);
        //add a key using putIfAbsent method; key=103 is absent so its added
        m.putIfAbsent(103, "Purple"); 
        System.out.println("\nAfter adding absent key 103 : " + m);
        m.remove(101, "Green"); 		        // remove key = 101 
        System.out.println("\nConcurrent Map after removing 101:" + m);
        
        m.putIfAbsent(101, "Brown"); 	// again add key = 101 since its absent
        System.out.println("\nAdd absent key 101:" + m);

        m.replace(101, "Brown", "Green"); 		        // replace value for key = 101 with 'Green' 
        System.out.println("\nReplace value at key 101:" + m); 
    } 
}
import java.util.concurrent.*; 
class Main { 
    public static void main(String[] args) { 
        //create and initialize concurrentHashMap
        ConcurrentHashMap m = new ConcurrentHashMap(); 
        m.put(100, "Red"); 
        m.put(101, "Green"); 
        m.put(102, "Blue"); 
        System.out.println("\nInitial Concurrent Map : " + m);
        //add a key using putIfAbsent method; key=103 is absent so its added
        m.putIfAbsent(103, "Purple"); 
        System.out.println("\nAfter adding absent key 103 : " + m);
        m.remove(101, "Green"); 		        // remove key = 101 
        System.out.println("\nConcurrent Map after removing 101:" + m);
        
        m.putIfAbsent(101, "Brown"); 	// again add key = 101 since its absent
        System.out.println("\nAdd absent key 101:" + m);

        m.replace(101, "Brown", "Green"); 		        // replace value for key = 101 with 'Green' 
        System.out.println("\nReplace value at key 101:" + m); 
    } 
}

Output:

Initial Concurrent Map : {100=Red, 101=Green, 102=Blue}
After adding absent key 103 : {100=Red, 101=Green, 102=Blue, 103=Purple}
Concurrent Map after removing 101:{100=Red, 102=Blue, 103=Purple}
Add absent key 101:{100=Red, 101=Brown, 102=Blue, 103=Purple}
Replace value at key 101:{100=Red, 101=Green, 102=Blue, 103=Purple}

Concurrent map in Java

Synchronized Map In Java

A synchronized map is a map that is thread-safe and is backed by a given map. In Java, the Synchronized map is obtained by using the synchronizedMap () method of java.util.Collections class. This method returns a synchronized map for a given map.

This returned synchronized map is used to access the backing map to achieve serial access.

The general declaration of synchronizedMap () method is:

public static <K, V> Map<K,V> synchronizedMap(Map<K,V> m)  

where m => is the backed map.

As already mentioned this method returns the synchronized view of map m.

The below Java program is an example of a synchronized map.

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        //declare and initialize a map
        Map<Integer, Integer> int_map = new HashMap<>();  
        int_map.put(1, 10);  
        int_map.put(2, 20);  
        int_map.put(3, 30);  
        int_map.put(4, 40);  
        int_map.put(5, 50);  
        //print the map
        System.out.println("Original (backed) Map: " + int_map);        
        //obtain synchronized map
        Map<Integer, Integer> sync_map = Collections.synchronizedMap(int_map);
        //remove an element from the map
        int_map.remove(3, 30);  
        //print the altered map
         System.out.println("\nSynchronized map after remove(3, 30):" + sync_map);  
         }  
}  

Output:

Original (backed) Map: {1=10, 2=20, 3=30, 4=40, 5=50}
Synchronized map after remove(3, 30):{1=10, 2=20, 4=40, 5=50}

Synchronized map in Java

Static Map In Java

A static map in Java is a map that is declared static just like a static variable. By declaring a map static, it becomes an accessible class variable without using the object.

There are two approaches to creating and initializing a static map in Java.

#1) Using A Static Variable

Here, we create a static map variable and instantiate it along with the declaration.

This approach is demonstrated in the following Java program.

import java.util.*;

class Main {
    //declare a static map variable and initialize it with declaration
	private static final Map<Integer, String> myMap = 
	            new HashMap<Integer, String>(){
                {
                    put(1, "India");
                    put(2, "Portugal");
                    put(3, "Germany");
                }
    };
	public static void main(String[] args) {
		//print the map
		System.out.println("Static map using static map variable:");
		System.out.println(myMap);
	}
}

Output:

Static map using static map variable:
{1=India, 2=Portugal, 3=Germany}

Using static block

#2) Using Static Block

In this, we create a static map variable. Then we create a static block and inside this static block, we initialize the map variable.

The program below demonstrates this.

import java.util.*; 
class Main { 
    // Declare the static map 
    private static Map<Integer, String> map; 
    // declare a static block and initialize static map
    static { 
        map = new HashMap<>(); 
        map.put(1, "Red"); 
        map.put(2, "Green"); 
        map.put(3, "Blue"); 
    } 
    public static void main(String[] args) { 
        System.out.println("Static Map using static block:");
        System.out.println(map); 
    } 
}

Output:

Static Map using static block:
{1=Red, 2=Green, 3=Blue}

Using static block

Conversion Of The List To Map

In this section, we will discuss the methods to convert the list to a map.

The two methods include:

Traditional Method

In the traditional method, each list element is copied to map using a for-each loop.

This implementation is shown below:

import java.util.*;  
public class Main {  
    public static void main(String[] args) {  
        //declare and initialize a list 
        List<String> colorsList = new ArrayList<String>();
        colorsList.add("Red");
        colorsList.add("Green");
        colorsList.add("Blue");
        colorsList.add("Brown");
        colorsList.add("White");
        System.out.println("The given list: " + colorsList);
        //declare a map
        Map<Integer, String> map = new HashMap<>();
        //initial Id(key)
        int i=1;
        //assign each list element to the map
        for (String color : colorsList) {
            map.put(i, color);
            i++;
        }
        //print the map
        System.out.println("Map generated from List:" + map);
        
    } 
}

Output:

The given list: [Red, Green, Blue, Brown, White]
Map generated from List:{1=Red, 2=Green, 3=Blue, 4=Brown, 5=White}

Traditional method

List To Map In Java 8

We can also use Java 8 method Collectors.mapOf () that will convert the given list into a map.

The below program demonstrates this.

import java.util.ArrayList; 
import java.util.LinkedHashMap; 
import java.util.List; 
import java.util.stream.Collectors; 
  
// class for list 
class Subject { 
  
    //sub_id => map key
    private Integer sub_id; 
  
    // sub_name => map value 
    private String sub_name; 
  
    // Subject constructor
    public Subject(Integer sub_id, String sub_name) { 
  
        // initialize sub_id and sub_name
        this.sub_id = sub_id; 
        this.sub_name = sub_name; 
    } 
  
    // return sub_id
    public Integer getSub_Id() { 
        return sub_id; 
    } 
  
    // return sub_name 
    public String getSub_Name() { 
        return sub_name; 
    } 
} 
  public class Main { 
    public static void main(String[] args) { 
  
        // create a list and add values to the list
        List<Subject> sub_list = new ArrayList<>(); 
  
        sub_list.add(new Subject(1, "Abacus")); 
        sub_list.add(new Subject(2, "Maths")); 
        sub_list.add(new Subject(3, "Physics")); 
        sub_list.add(new Subject(3, "Chemistry")); 
        
        //use Java 8 Collectors.toMap() method to create a map and assign list elements to it 
        LinkedHashMap<Integer, String> 
            sub_map = sub_list.stream() 
               .collect( Collectors.toMap(Subject::getSub_Id, 
               Subject::getSub_Name,(x, y) -> x + ", " + y, LinkedHashMap::new)); 
  
        //print the map
        System.out.println("Map obtained from list : " + sub_map);
        
    } 
}

Output:

Map obtained from list : {1=Abacus, 2=Maths, 3=Physics, Chemistry}

List to Map in Java 8

In this program, we have a class Subject that acts as a list class. The class Subject has two fields i.e. sub_id and sub_name. We have methods to read the field values from the class. In the main function, we create objects of this class and construct a list.

This list is then converted to the map by using the Collectors.MapOf method that takes the elements one by one. It also takes the sub_Id as the key to the map. Finally, the map that has sub_Id as key and Sub_Name as value is generated.

Convert Map To String In Java

A map collection can be converted to a string using two approaches:

Using StringBuilder

Here we create a StringBuilder object and then copy the key-value pairs of the map into the StringBuilder object. Then we convert the StringBuilder object into a string.

The below program shows the Java code to convert the map to the string.

import java.util.*; 
import java.util.stream.Collectors; 

public class Main
{
        public static void main(String[] args) {
        //create and initialize a map
        Map<Integer, String> numberNames = new HashMap<>();
        numberNames.put(10, "Ten");
        numberNames.put(20, "Twenty");
        numberNames.put(30, "Thirty");
        numberNames.put(40, "Forty");
        //print the given map
        System.out.println("The given map: " + numberNames);
        //create a StringBuilder object to store string
        StringBuilder map_String = new StringBuilder("{");
        //append key-value pair of map to StringBuilder object
        for (Integer key : numberNames.keySet()) {
            map_String.append(key + "=" + numberNames.get(key) + ", ");
        }
        map_String.delete(map_String.length()-2, map_String.length()).append("}");
        //print the string from StringBuilder        
        System.out.println("\nThe string representation of map:");
        System.out.println(map_String.toString());
   }
}

Output:

The given map: {20=Twenty, 40=Forty, 10=Ten, 30=Thirty}
The string representation of map:
{20=Twenty, 40=Forty, 10=Ten, 30=Thirty}

Using StringBuilder

Using Java 8 Streams

In this method, we create a stream out of the map keys and then convert it to the string.

The program given below shows the conversion of the map to a string using streams.

import java.util.*; 
import java.util.stream.Collectors; 

public class Main{
       public static void main(String[] args) {
       //create and initialize a map
       Map<Integer, String> numberNames = new HashMap<>();
        numberNames.put(10, "Ten");
        numberNames.put(20, "Twenty");
        numberNames.put(30, "Thirty");
        numberNames.put(40, "Forty");
        //print the given map
        System.out.println("The given map: " + numberNames);
        String map_String = numberNames.keySet().stream()
        .map(key -> key + "=" + numberNames.get(key))
        .collect(Collectors.joining(", ", "{", "}"));
        //print the string         
        System.out.println("\nThe string representation of map:");
        System.out.println(map_String);
	}
}

Output:

The given map: {20=Twenty, 40=Forty, 10=Ten, 30=Thirty}
The string representation of map:
{20=Twenty, 40=Forty, 10=Ten, 30=Thirty}

Using Java 8 streams

Convert Map To List In Java

A map consists of keys and values whereas a list is a sequence of individual elements. When converting the map to a list, we usually convert keys into a list of keys and values into a list of values.

The following Java program shows this conversion.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        //declare a map and initialize it
        Map<Integer, String> color_map = new HashMap<>();
        color_map.put(10, "red");
        color_map.put(20, "green");
        color_map.put(30, "blue");
        color_map.put(40, "cyan");
        color_map.put(50, "magenta");
        //print the list of keys using map.keySet() method
        System.out.println("List of keys from the given map:");
        List<Integer> key_list = new ArrayList(color_map.keySet());
        System.out.println(key_list);

        //print the list of values using map.values() method
        System.out.println("\nList of values from the given map:");
		List<String> val_list = new ArrayList(color_map.values());
		System.out.println(val_list);
    }
}

Output:

List of keys from the given map:
[50, 20, 40, 10, 30]
List of values from the given map:
[magenta, green, cyan, red, blue]

Convert the map to list in Java

Dictionary Vs. Map In Java

Let’s discuss some of the major differences between a dictionary and a map in Java.

DictionaryMap
Dictionary is an abstract class.The map is an interface.
Classes and methods used by the dictionary class predate collections framework.Classes and methods used by map classes are part of the collection framework.
If a class extends the dictionary, it cannot extend any other class since Java supports only single inheritanceThe map is an interface, so a class can inherit from the map and other interfaces
Old implementation. Almost obsolete in newer versions of Java.The map interface has replaced dictionary implementation.

Frequently Asked Questions

Q #1) Why do we use a map interface in Java?

Answer: The map is an interface in Java that is implemented by classes storing data as key-value pairs. Map interface provides operations/methods that can be performed on key-value pairs like insertion, updating, deletion, etc.

Q #2) What does MAP mean in Java?

Answer: A map in Java represents a mapping of a key with a specific value. A Java map stores these key-value pairs in a map. We can look up and retrieve the value associated with a key just by using the key in the map.

A map is implemented in Java using an interface that is not part of the Collection interface. But the map is a collection.

Q #3) What is MAP get?

Answer: The get () is a method provided by a map interface in Java that is used to retrieve the value associated with a particular key provided as an argument to the get () method. If the value is not present, a null is returned.

Q #4) Is the map a collection?

Answer: Although the map is viewed as a collection in general, it doesn’t implement a Collection interface. Some of the implementations of map, like treemap does not support null values or keys.

Q #5) What is the difference between set and map?

Answer: Set is a collection of keys only whereas the map is a collection of key-value pairs. While the set does not allow null values, some of the map implementations allow null values.

Set does not allow duplicate keys. The map may allow duplicate values but keys must be unique. Set is usually used when we want to store a collection of unique elements. The map can be used when we need to store data in the form of key-value pairs.

Conclusion

In this tutorial, we have discussed the basics of the map interface. We have also seen the various methods and all other details related to the map interface in Java. We came to know that there are various implementations of map interfaces including treemap, hashmap, etc.

In our upcoming tutorials, we will discuss this map implementation in more detail.

=> Visit Here To Learn Java From Scratch.

Was this helpful?

Thanks for your feedback!

Leave a Comment