×

Map of Map in Java

The map is now a Java interface for mapping keys to values. It is frequently necessary to use Map of Map (nested Map).

Nested Maps are useful in various situations, including keeping students' names together with respective course Ids. In this example, we build a Map with a key, i.e., course, and value, i.e., another Map with a key, i.e., Id, and value, i.e., the patient's name.

To make a Map of Map in Java, take these steps:

  • For every course, sum the number of students from either the user.
  • Fill in the student registration for all classes based on the user's input.
  • Filling up the primary Map with the course name like a keyword and the user-created Map as a value.
  • We begin inside the for a loop by converting all of the Map's values into an ArrayList of class Object.
  • Following that, we use the get() function to retrieve the item in the list and the information from the Map relating to this item for displaying.

MapEx.java

// this program is for map of map in Java
//importing the required packages
import java.util.HashMap;  
import java.util.Map;  
import java.util.*;  
//To make a MapOfMap Sample, define the class MapOfMapEx. 
public class MapEx {  
    // main section of the program 
        public static void main(String[] args) {          
        //  the variables are then declared  
        int sizes1 = 0;  
        int sizes2 = 0;  
        // develop a map of all BC students which should contain their names and IDs. 
                Map<Object,String> bcStudents = new HashMap<Object, String>();  
            // design a map for MC students that will contain their names and IDs.
                Map<Object,String> mcStudents = new HashMap<Object, String>();  
                // an object is created for the scanner class  
        Scanner sc = new Scanner(System.in);  
        System.out.println("Please enter the students in Bc.");  
        sizes1 = Integer.parseInt(sc.nextLine());  
        System.out.println("Please enter the students in Mc.");  
        sizes2 = Integer.parseInt(sc.nextLine());  
        // Fill up the bcStudents Map using user-provided data.        
        for(int i = 1; i <= sizes1; i++){  
            int ids= 100;  
            String names = "";  
            System.out.println("Please enter the name of the " + i + "st student in BC:");  
            names = sc.nextLine();  
            System.out.println("The Id of the Student is:  = " + (ids+i) + "    Students Names = "+names);  
            ids = ids + i;  
            bcStudents.put(Integer.valueOf(ids), names);  
        }  
        // fill mcaStudents Map by taking input from the user          
        for(int i = 1; i <= sizes2; i++){  
            int ids= 100;  
            String names = "";  
            System.out.println("Please enter the name of the " + i + "st student of MCA:");  
            names = sc.nextLine();  
            System.out.println("Student Id = " + (ids+i) + "   Student Name = "+names);  
            ids = ids + i;  
            mcStudents.put(Integer.valueOf(ids), names);           
        }  
        // build a map including information on BC and MC students.
        Map<String, Object> students1 = new HashMap<String, Object>();  
        students1.put("BC", bcStudents);  
        students1.put("MC", mcStudents);  
        // the mapping of the student is printed
                System.out.println("The Map of Map is :   " + students1);   
                // the student's names is printed
                for (int i = 0; i < students1.size(); i++){  
                    ArrayList<Object> datas = new ArrayList<Object>(students1.keySet());  
                    Object object = datas.get(i);  
                    System.out.println("Courses: " + object + " Student: " + students1.get(object));  
                }  
        // close Scanner class object  
        sc.close();              
}  
}  

Output

Please enter the students in Bc.
3
Please enter the students in Mc.
3
Please enter the name of the 1st student in BC:
Sai
The Id of the Student is:  = 101    Students Names = Sai
Please enter the name of the 2st student in BC:
Ram
The Id of the Student is:  = 102    Students Names = Ram
Please enter the name of the 3st student in BC:
Raghu
The Id of the Student is:  = 103    Students Names = Raghu
Please enter the name of the 1st student of MCA:
Anusha
Student Id = 101   Student Name = Anusha
Please enter the name of the 2st student of MCA:
Sita
Student Id = 102   Student Name = Sita
Please enter the name of the 3st student of MCA:
Latha
Student Id = 103   Student Name = Latha
The Map of Map is :   {BC={101=Sai, 102=Ram, 103=Raghu}, MC={101=Anusha, 102=Sita, 103=Latha}}
Courses: BC Student: {101=Sai, 102=Ram, 103=Raghu}
Courses: MC Student: {101=Anusha, 102=Sita, 103=Latha}

Related Topics

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Hogben Numbers in Java

In this section, we will discover what the Hogben number is and develop Java programs that compute it. Java coding interviews and academic exams typically involve questions about the Hogben...

3 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

Program to Find Square Root of a Number Without sqrt Method in Java

The Java Math class sqrt () function can be used to determine the square root of a number. In this section, we'll write a Java program to find a number's...

3 minutes read.

How to Convert boolean to String in Java

How to Convert boolean to String in Java There are two methods to convert boolean to String. Using valueOf(boolean) method Using toString(boolean) method For both the above methods, if the passes Boolean...

2 minutes read.

Java Integer compareTo() method

The compareTo() method of Integer class compares two Integer objects numerically. Syntax public static int compareTo(int anotherInteger) Parameters The parameter ‘anotherInteger’ represents the Integer to be compared. Specified by This method is specified by compareTo in...

2 minutes read.

Java Math asin() Method

The asin() method of Math class computes the trigonometric Arc Sine (inverse of sine ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double asin(double a) Parameters: The...

1 minute read.

Check whether Java is installed or not

As we know that there are various operating systems, to check whether Java is installed or not in Windows and Mac we use the following ways.           Windows Operating System: There are several...

2 minutes read.

Add Time in Java

Before Java 8, java.util.Date was one of the most usually involved classes for addressing date-time values in java. Then Java 8 presented java.time.LocalDateTime and java.time.ZonedDateTime. Java 8 likewise permits us...

6 minutes read.

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed...

8 minutes read.

Normal and Trace of a Matrix in Java

Normal of a matrix The square root of the total squares of each element in a matrix is known as the matrix's normal. Think of the following matrix as an example. Example: [[1,2,3]  ...

3 minutes read.

Java LinkedList

LinkedList Java The Java LinkedList is used to store the elements by using a doubly linked list. It contains the duplicate items, also maintains the order of the insertion, the class...

5 minutes read.

Java LinkedHashMap

LinkedHashMap implements the Map interface. It inherits the HashMap class. Some essential features of LinkedHashMap are: It contains the values based on the keys. It maintains the order of insertion. It contains unique...

5 minutes read.

Java Generate Random String

Java Generate Random String In this tutorial, we will learn about to generate random string in Java. Random generation strings mean any string will be generated, which does not follow any...

7 minutes read.

Inheritance Program in Java

Inheritance Program in Java Inheritance is one of the important pillars of Object-Oriented Programming that facilitates parent-child relationships in programming. Using inheritance, we can create a new class with the help...

7 minutes read.

Java Program to Sort an Array of 0's, 1's, and 2’s | Dutch National Flag Problem in Java

The famed Dutch computer programmer Edsger Dijkstra's Dutch Nation Flag (DNF) challenge ranks among the most well-known programming challenges. The Dutch tricolor flag, comprising red, white, and blue, is the...

3 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 minutes read.

Java Transient Keyword

An object in Java can be turned into a stream of bytes using serialization. The data of the instance and the kind of data saved in that instance are both...

3 minutes read.