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
To add multiple values for a specific key, you can use the put() method:
multiMap.put("key", new ArrayList
To retrieve the values, you can use the get() method to obtain the ArrayList and then iterate over it:
List
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).
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