Home >Java >javaTutorial >How to Store Multiple Values with the Same Key in a HashMap?
Creating HashMaps with Multiple Values per Key
In some scenarios, it may be necessary to store multiple values with the same key in a HashMap. Although Java's HashMap does not natively support this, there are several alternative approaches to achieve this functionality.
1. Map with List as Value
One option is to create a HashMap where the values are lists. This allows for multiple values to be associated with a single key. For instance:
Map<String, List<Person>> peopleByForename = new HashMap<>();
2. Wrapper Class
An alternative is to define a wrapper class that holds the multiple values. This wrapper can then be used as the value in the HashMap:
class Wrapper { private Person person1; private Person person2; public Wrapper(Person person1, Person person2) { this.person1 = person1; this.person2 = person2; } // Getter methods } Map<String, Wrapper> peopleByForename = new HashMap<>();
3. Tuples
If your programming language supports tuples, you can utilize them as keys or values in a HashMap. For example:
Map<String, Tuple2<Person, Person>> peopleByForename = new HashMap<>();
4. Multiple Maps
Finally, another strategy is to use separate maps for each value type:
Map<String, Person> firstPersonByForename = new HashMap<>(); Map<String, Person> secondPersonByForename = new HashMap<>();
Examples
Considering the example scenario of a HashMap with a userId, clientID, and timeStamp:
Option 1: Map with List as Value
Map<Integer, List<Pair<String, Long>>> data = new HashMap<>(); data.put(1, Arrays.asList(new Pair<>("client-1", System.currentTimeMillis()))); data.put(1, Arrays.asList(new Pair<>("client-2", System.currentTimeMillis())));
Option 2: Wrapper Class
class Data { private Integer userId; private String clientID; private Long timeStamp; public Data(Integer userId, String clientID, Long timeStamp) { this.userId = userId; this.clientID = clientID; this.timeStamp = timeStamp; } } Map<Integer, Data> data = new HashMap<>(); data.put(1, new Data(1, "client-1", System.currentTimeMillis())); data.put(1, new Data(1, "client-2", System.currentTimeMillis()));
The choice of approach depends on the specific requirements of your application and the programming language being used.
The above is the detailed content of How to Store Multiple Values with the Same Key in a HashMap?. For more information, please follow other related articles on the PHP Chinese website!