Home >Java >javaTutorial >How to Map Multiple Values to a Single Key in a Java HashMap?

How to Map Multiple Values to a Single Key in a Java HashMap?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 02:14:28306browse

How to Map Multiple Values to a Single Key in a Java HashMap?

Mapping Multiple Values to a Single Key in HashMap

In Java's HashMap, each key is associated with a single value. However, there are scenarios where you may need to map multiple values to a single key. Here's how you can achieve this:

The MultiValueMap Approach:

The simplest and most straightforward approach is to use a Map of List. This involves creating a HashMap where the values are ArrayLists containing multiple values. For instance:

<code class="java">Map<Object, ArrayList<Object>> multiMap = new HashMap<>();</code>

To add multiple values for a specific key, you can use the put() method:

<code class="java">multiMap.put("key", new ArrayList<Object>() {{
    add("value1");
    add("value2");
    add("value3");
}});</code>

To retrieve the values, you can use the get() method to obtain the ArrayList and then iterate over it:

<code class="java">List<Object> values = multiMap.get("key");
for (Object value : values) {
    // Do something with the value
}</code>

In this example, values will contain a List with ["value1", "value2", "value3"]. You can then access the desired value based on its index (i.e., values.get(2) for the third value).

The above is the detailed content of How to Map Multiple Values to a Single Key in a Java HashMap?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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