HashMap with multiple values under the same key

To store multiple values under the same key in a HashMap in Java, you can use a List or an array as the value for the key. Here's an example of how to use a List to store multiple values under the same key in a HashMap:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        HashMap<String, List<String>> map = new HashMap<>();
        map.put("key1", List.of("value1", "value2"));
        map.put("key2", List.of("value3", "value4"));

        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    }
}

This will output the following:

key1: [value1, value2]
key2: [value3, value4]

You can also use an array to store multiple values under the same key in a HashMap. Here's an example of how to do this:

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String[]> map = new HashMap<>();
        map.put("key1", new String[] {"value1", "value2"});
        map.put("key2", new String[] {"value3", "value4"});

        for (String key : map.keySet()) {
            System.out.println(key + ": " + String.join(", ", map.get(key)));
        }
    }
}

This will also output the same result as the previous example.

In either case, the HashMap will allow you to store multiple values under the same key, and you can retrieve the values for a key using the get method.