HashMap to Store Multiple Values per Key
HashMap is a widely used data structure that maps keys to values. However, it is typically designed to store a single value for each key. This limitation may not always align with real-world requirements, where the need arises to store multiple values under the same key.
Approaches to Implement Multiple Values in a HashMap
If the requirement is to store exactly two values per key, several approaches can be considered:
Example Implementations
Using List as Value:
// Initialize the HashMap Map<String, List<Person>> peopleByForename = new HashMap<>(); // Populate the HashMap List<Person> people = new ArrayList<>(); people.add(new Person("Bob Smith")); people.add(new Person("Bob Jones")); peopleByForename.put("Bob", people); // Retrieve values List<Person> bobs = peopleByForename.get("Bob"); Person bob1 = bobs.get(0); Person bob2 = bobs.get(1);
Using Wrapper Class:
// Define the wrapper class class Wrapper { private Person person1; private Person person2; public Wrapper(Person person1, Person person2) { this.person1 = person1; this.person2 = person2; } public Person getPerson1() { return person1; } public Person getPerson2() { return person2; } } // Initialize the HashMap Map<String, Wrapper> peopleByForename = new HashMap<>(); // Populate the HashMap peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"), new Person("Bob Jones"))); // Retrieve values Wrapper bobs = peopleByForename.get("Bob"); Person bob1 = bobs.getPerson1(); Person bob2 = bobs.getPerson2();
Using Tuple Class:
// Initialize the HashMap Map<String, Tuple2<Person, Person>> peopleByForename = new HashMap<>(); // Populate the HashMap peopleByForename.put("Bob", new Tuple2<>(new Person("Bob Smith"), new Person("Bob Jones"))); // Retrieve values Tuple2<Person, Person> bobs = peopleByForename.get("Bob"); Person bob1 = bobs.Item1; Person bob2 = bobs.Item2;
The above is the detailed content of How Can I Store Multiple Values per Key in a HashMap?. For more information, please follow other related articles on the PHP Chinese website!