![]() |
In Java, HashMap is used to store the data in Key – Value pairs. One key object is associated with one value object. Below is the syntax for inserting the values into HashMap. HashMap<String, Integer> hm = new HashMap<String, Integer>(); hm.put("one", 100); hm.put("two", 200); hm.put("three", 300); If we print the above HashMap, the output will be like the below. HashMap does not guarantee the order of the values that are stored. three=300 one=100 two=200 Now, we want to insert another value into the same key. But we cannot insert the duplicate key because it will replace the value of the corresponding key like below. HashMap<String, Integer> hm = new HashMap<String, Integer>(); hm.put("one", 100); hm.put("one", 1000); hm.put("three", 300); If we print the above HashMap, the output will be like the below. three=300 one=1000 Here, the value 100 is replaced with 1000. In these cases, we can use Collections such as list, set, etc. to insert multiple values into the same key in HashMap. Syntax: HashMap<String, List<String>> hm = new HashMap<String, List<String>>(); HashMap<String, Set<Integer>> hm = new HashMap<String, Set<Integer>>(); Example:To understand the concept, we will take the below example in which the input will be students and sports database. The output should print each student’s name followed by the sports they are interested in. Input database:
Output: {Neha=[3-Caroms], John=[3-Caroms, 1-Tennis], Ram=[1-Tennis, 4-Cricket, 2-Chess]} Program: First, we need to create a Student class that is a Java bean to define the variables and their getter-setter methods. Student.java Java
Now, we need to create the main class to run the program. For simplicity, instead of reading the values from the database, we are creating multiple student objects inside the main method. SportsData.java: Java
Execution:
Output: The output will be as follows. ![]()
In this way, we can insert multiple values associated with the same key into the HashMap using Collections. |
Reffered: https://www.geeksforgeeks.org
Java |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |