HashMap: Managing Multiple Values for a Single Key
Question:
Is it possible to store and retrieve multiple values associated with the same key in a HashMap? If so, how can I access the third value for the first key?
Answer:
While a standard HashMap cannot store duplicate keys, it is possible to implement a HashMap-like structure that allows multiple values for a single key using a Map of List. Here's a plain Java solution:
<code class="java">import java.util.HashMap; import java.util.ArrayList; public class MultiValueMapDemo { public static void main(String[] args) { // Create a Map of List to store key-value pairs Map<Object, ArrayList<Object>> multiMap = new HashMap<>(); // Add key-value pairs multiMap.computeIfAbsent("keyA", k -> new ArrayList<>()).add("value1"); multiMap.computeIfAbsent("keyA", k -> new ArrayList<>()).add("value2"); multiMap.computeIfAbsent("keyA", k -> new ArrayList<>()).add("value3"); // Get the third value for the first key Object thirdValue = multiMap.get("keyA").get(2); System.out.println("Third value for keyA: " + thirdValue); } }</code>
This approach creates a HashMap where the values associated with a key are stored in a List. To access a specific value, you can use the get() method on the List object retrieved from the HashMap. In this example, the third value for the key "keyA" is accessed using multiMap.get("keyA").get(2).
The above is the detailed content of How can you store and retrieve multiple values associated with the same key in a HashMap?. For more information, please follow other related articles on the PHP Chinese website!