Home >Java >javaTutorial >Can you store multiple string values under the same key in a map?
In programming, using a dictionary or map is a common way to store key-value pairs. Typically, a map associates a key with a single value. However, some scenarios require storing multiple string values associated with the same key. Let's explore whether this is possible in a map.
Unfortunately, it's not directly possible to store more than one string value for the same key in a standard map. Maps are designed to be collections of unique key-value pairs, where each key is associated with a single value.
Instead of trying to store multiple strings in a map, the recommended solution is to create a custom object that represents the data you want to store. In this case, you could create a ContactInformation object that contains properties for number, name, address, and phone. Then, you can store the ContactInformation object as the value in the map.
For example:
<code class="java">public class ContactInformation { private String number; private String name; private String address; private String phone; // Constructor, getters, and setters } Map<String, ContactInformation> contactMap = new HashMap<>();</code>
By using an object to represent the multiple string values, you can effectively store and retrieve the data associated with each key in the map.
The above is the detailed content of Can you store multiple string values under the same key in a map?. For more information, please follow other related articles on the PHP Chinese website!