Home > Java > javaTutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-26 02:14:28
Original
227 people have browsed it

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!