×

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

Virtual Function in Java

In the Operated Oriented Programming language, a virtual function or virtual method is a collection of functions that overrides the functionality of a function in an inheriting class with the same...

4 minutes read.

Modules in Golang

Modules are a way to manage dependency versions and enable reproducible builds of Go programs. They were introduced in Go 1.11 and are now the recommended way to manage dependencies...

4 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

Java Code Optimization

We encounter the idea of optimization while working on any Java application. It is essential that the code we write is not only clear and error-free but also optimized, meaning...

9 minutes read.

Java Else Keyword

The else statement specifies a section of Java code that will run if an if statement's condition is false.The following conditional statements can be used in Java:To provide a block...

3 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java Plot

Java Plot is a phrase in Java that is mostly used for plotting coordinates on a cartesian plane. Plotting graphs in Java is accomplished through the use of various core...

3 minutes read.

Java Architecture

Java architecture is a combination of three parts they are JVM, JRE and JDK. These components will help in the functioning of the java programs. The process of code interpretation...

6 minutes read.

Recursion Program in Java

The recursion program in Java demonstrates the usage of recursion. The process by which a function/ method calls itself, again and again, is called recursion. Each recursive call is pushed...

10 minutes read.

Basic Terms in Multithreading

To understand the terms of multithreading, we must have knowledge about concurrency, processes, and threads. Concurrency The concurrency stands for performing multiple tasks at the same time. In the process communication, the operating system permits the process...

8 minutes read.

Null Pointer Exception in Java

It is a runtime error exception. The null value is allocated to the object reference in this exception. We will explicitly throw this null pointer exception when the program wants...

3 minutes read.

Java vs Node.js

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java Math atan() Method

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

2 minutes read.

Java FileOutputStream

What is FileOutputStream?When we need raw stream data written into a file, we need to look for another option: FileOutputStream. It is used when the file's data is byte-oriented. It comes under...

4 minutes read.

Java Math acos() Method

The acos() method of Math class computes the trigonometric Arc Cosine (inverse of cosine ) of an angle. The value returned is between 0.0 to pi. Syntax: public static double acos(double a) Parameters: The...

1 minute read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Series Program in Java

Series Program in Java The series program in Java is written to print the mathematical series such as the Fibonacci series, Pell series, etc. A few of the renowned series are...

12 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.