Introduction
Java is a popular programming language that is widely used in developing various applications. One of the most commonly used data structures in Java is the Map interface, which allows us to store and manipulate key-value pairs. In this article, we will discuss how to create a Map in Map example in Java.
What is a Map in Java?
A Map is an interface in Java that represents a mapping between a key and a value. It is similar to a dictionary in Python or an object in JavaScript. The Map interface is implemented by several classes in Java such as HashMap, TreeMap, and LinkedHashMap.
How to Create a Map in Java?
To create a Map in Java, we can use any of the classes that implement the Map interface. Let’s take the example of a HashMap.
Map map = new HashMap<>();
In the above code, we have created a HashMap that stores key-value pairs where the key is of type String and the value is of type Integer.
How to Add Values to a Map in Java?
To add values to a Map in Java, we can use the put() method. Let’s see an example.
map.put("John", 30); map.put("Jane", 25);
In the above code, we have added two key-value pairs to the HashMap. The key “John” has a value of 30 and the key “Jane” has a value of 25.
How to Retrieve Values from a Map in Java?
To retrieve values from a Map in Java, we can use the get() method. Let’s see an example.
int age = map.get("John"); System.out.println("John's age is " + age);
In the above code, we have retrieved the value associated with the key “John” and stored it in the variable age. We have then printed the age using the System.out.println() method.
What is a Map in Map in Java?
A Map in Map is a data structure that allows us to store a Map as the value of another Map. Let’s take an example.
Map> mapInMap = new HashMap<>(); Map johnMap = new HashMap<>(); johnMap.put("Maths", 90); johnMap.put("Science", 85); mapInMap.put("John", johnMap); Map janeMap = new HashMap<>(); janeMap.put("Maths", 95); janeMap.put("Science", 80); mapInMap.put("Jane", janeMap);
In the above code, we have created a Map in Map where the key is of type String and the value is of type Map
How to Retrieve Values from a Map in Map in Java?
To retrieve values from a Map in Map in Java, we can use the get() method twice. Let’s see an example.
int mathsMarks = mapInMap.get("John").get("Maths"); System.out.println("John's Maths marks are " + mathsMarks);
In the above code, we have retrieved the value associated with the key “John” from the Map in Map. We have then retrieved the value associated with the key “Maths” from the Map that is stored as the value of “John” in the Map in Map. We have then printed the maths marks using the System.out.println() method.
Conclusion
In this article, we discussed how to create a Map in Map example in Java. We also learned how to add values to a Map, retrieve values from a Map, and retrieve values from a Map in Map. Maps are an important data structure in Java and are widely used in various applications.