Home >Java >javaTutorial >How to Store Multiple String Values for a Single Key in a Java Map?

How to Store Multiple String Values for a Single Key in a Java Map?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 02:31:31406browse

How to Store Multiple String Values for a Single Key in a Java Map?

Storing Multiple Strings in a Map

In Java, you can encounter a scenario where you need to store more than one string value for a key in a map. However, Java's standard Map interface does not support storing multiple values for a single key.

Problem:

Is it possible to set more than two key-value pairs in a Map? For instance, can you create a Map structure like the following:

<code class="java">Map<String,String,String,String></code>

where each key ("number") is associated with multiple values ("name", "address", "phone") that are displayed together?

Answer:

The solution to this problem is to avoid using multiple keys and instead utilize an object to hold the various string values. Consider creating a ContactInformation class that encapsulates the name, address, and phone number:

<code class="java">public class ContactInformation {
    private String name;
    private String address;
    private String phone;

    // Constructor and getters/setters
}</code>

You can then use this object as the value in your Map:

<code class="java">Map<String, ContactInformation> contacts = new HashMap<>();

ContactInformation contact = new ContactInformation();
contact.setName("John Doe");
contact.setAddress("123 Main Street");
contact.setPhone("(555) 123-4567");

contacts.put("number", contact);</code>

When you need to access the values, you can retrieve the ContactInformation object from the map and access its properties:

<code class="java">ContactInformation contact = contacts.get("number");
String name = contact.getName();
String address = contact.getAddress();
String phone = contact.getPhone();</code>

By using an object to encapsulate the multiple string values, you avoid the limitations of Java's Map interface and effectively store and retrieve related information.

The above is the detailed content of How to Store Multiple String Values for a Single Key in a Java Map?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn