Robert Strauch
Robert Strauch

Reputation: 12896

Assign multiple values per key in a Java Map

Creating a standard Map in Java is easy.

Map<Integer, String> map = new HashMap<>();
map.put(1, "Name 1");
map.put(2, "Name 2");

Now I need to "extend" this standard map approach, so that each key can represent multiple values, e.g. like this:

Map<Integer, String, String, String> map = new HashMap<>();
map.put(1, "Name 1", "Address 1", "ZIP Code 1");
map.put(2, "Name 2", "Address 2", "ZIP Code 2");

Is there any "standard" implementation or library which provides such a feature? I'm aware of e.g. Apache Commons MultiValuedMap (https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiValuedMap.html) but this doesn't seem to fit the above use case.

Upvotes: 1

Views: 973

Answers (4)

Kent S.
Kent S.

Reputation: 1

com.google.common.collect.ArrayListMultimap already does this in a generic fashion.

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114440

A better option is likely to make an object to contain your info:

public class Person
{
    private String name;
    private String address;
    private String zip;

    ...
}

You can use the class as your value type:

Map<Integer, Person> map = new HashMap<>();
map.put(1, new Person("Name 1", "Address 1", "ZIP Code 1"));
map.put(2, new Person("Name 2", "Address 2", "ZIP Code 2"));

As of java 16, you can use a record class to make the container:

record Person(String name, String address, String zip) {}

Upvotes: 6

Prophet
Prophet

Reputation: 33361

Your value can be a List of Strings, like this:

Map<Integer, List<String>> map = new HashMap<>();

The more readable way is to initialize a value list and then put it to the map as a value:

ArrayList<String> value1 = new ArrayList<String>();
value1.add("Name 1");
value1.add("Address 1");
value1.add("ZIP Code 1");

ArrayList<String> value2 = new ArrayList<String>();
value1.add("Name 2");
value1.add("Address 2");
value1.add("ZIP Code 2");

Map<Integer, List<String>> map = new HashMap<>();
map.put(1, value1);
map.put(2, value2);

But you can initialize it inline too

Map<Integer, List<String>> map = new HashMap<>();
map.put(1,  new ArrayList<>(Arrays.asList("Name 1", "Address 1", "ZIP Code 1")));
map.put(2,  new ArrayList<>(Arrays.asList("Name 2", "Address 2", "ZIP Code 2")));

Upvotes: 3

TSHen
TSHen

Reputation: 1

I think you should create a nested DTO class that contains those attributes.

Upvotes: -1

Related Questions