Monday, November 18, 2024
Google search engine
HomeLanguagesJavaCreate HashMap with Multiple Values Associated with the Same Key in Java

Create HashMap with Multiple Values Associated with the Same Key in Java

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:

Student Name

Sport ID

Sport Name

Ram 1 Tennis
John 3 Caroms
John 1 Tennis
Neha 3 Caroms
Ram 4 Cricket
Ram 2 Chess

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




class Student {
    
    String name;
    String sport;
    String sportId;
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getSportId() {
        return sportId;
    }
  
    public void setSportId(String sportId) {
        this.sportId = sportId;
    }
  
    public String getSport() {
        return sport;
    }
  
    public void setSport(String sport) {
        this.sport = sport;
    }
  
    Student(String name, String sportId, String sport) {
        this.name = name;
        this.sportId = sportId;
        this.sport = sport;
    }
  
}


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




import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
  
public class SportsData {
  
    public static void main(String[] args) {
          
        Student s1 = new Student("Ram", "1", "Tennis");
        Student s2 = new Student("John", "3", "Caroms");
        Student s3 = new Student("John", "1", "Tennis");
        Student s4 = new Student("Neha", "3", "Caroms");
        Student s5 = new Student("Ram", "4", "Cricket");
        Student s6 = new Student("Ram", "2", "Chess");
          
        List<Student> l = new ArrayList<Student>(Arrays.asList(s1,s2,s3,s4,s5,s6));
        HashMap<String, List<String>> hm = new HashMap<String, List<String>>(); 
        
        for(Student s : l) {            
            if (hm.containsKey(s.name)) {
                hm.get(s.name).add(s.sportId+"-"+s.sport);
            } else {
                hm.put(s.name, new ArrayList<String>());
                hm.get(s.name).add(s.sportId+"-"+s.sport);
            }
        }
        System.out.println(hm);
    }
  
}


Execution:

  • When we run the SportsData.java class, it will create 6 student objects with the respective details.
  • To loop through the student objects, we are creating an ArrayList to store all the objects.
  • Now, we need to associate each student’s name with their respective sport. To achieve this, we are using HashMap.
  • By iterating the ArrayList, we are inserting the data – Student Name as Key and Sport ID, Sport Name as Value, in the HashMap.
  • While inserting, we need to check the Key object, if it is already present or not using the containsKey() method.
  • If the Key object is new, we need to create a new ArrayList<String> as a value and then insert the Sports data in the HashMap.

Output:

The output will be as follows.

 HashMap with Multiple Values Associated with the Same Key Output

 

In this way, we can insert multiple values associated with the same key into the HashMap using Collections.

RELATED ARTICLES

Most Popular

Recent Comments