Home > Java > javaTutorial > How can you store and retrieve multiple values associated with the same key in a HashMap?

How can you store and retrieve multiple values associated with the same key in a HashMap?

DDD
Release: 2024-10-25 10:04:02
Original
1075 people have browsed it

How can you store and retrieve multiple values associated with the same key in a HashMap?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template