Storing Multiple Strings in a Map
Question: Can you store more than one string value in a single Map entry? For instance, consider the map:
<code class="java">Map<String, String, String, String> myMap;</code>
Can you associate each key with multiple values, such as number, name, address, and phone, and retrieve them together?
Answer:
Creating a map with multiple string values for a single key is not directly possible in Java. Maps are structured to associate a single value with each key.
Solution:
To achieve your desired functionality, you should create a custom object to represent the collection of data associated with each key. For your example, you could define a ContactInformation class containing properties for number, name, address, and phone.
Then, instead of storing multiple string values in the map, you would store the ContactInformation object:
<code class="java">Map<String, ContactInformation> myMap;</code>
Each key in the map would now associate with a single ContactInformation object, containing the multiple string values you require.
This solution allows you to group related data into a single object, ensuring that the values are retrieved together and maintaining a well-structured and type-safe design.
The above is the detailed content of Can you store multiple strings in a single Map entry in Java?. For more information, please follow other related articles on the PHP Chinese website!