"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-08
Browse:905

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:

Map> multiMap = new HashMap();

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

multiMap.put("key", new ArrayList() {{
    add("value1");
    add("value2");
    add("value3");
}});

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

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

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).

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3