0

I'd like to have a Java collection that is like a Map but with multiple keys and multiple values.

Sample:

Lets say we have 3 keys and then 3 values for an element.

set (key ("G", "Merc", "SUV"), val ("silver", "400", "100.000"));

val v = get (key ("A4", "Audi", "Sedan"))

Does such a collection exist in some library?

3
  • have a list as key and value. Possible? Commented Dec 3, 2019 at 15:23
  • 1
    It does not. You either make your own, or use custom objects to contain multiple values, then use those as keys/values Commented Dec 3, 2019 at 15:23
  • 1
    you mean something like HashMap< Set<String>, Set<String>> ? Commented Dec 3, 2019 at 15:26

3 Answers 3

2

The easiest way, and the way I'd recommend, is to simply create 2 java classes, one will be key, the other will be the value.

class Key {
    String str1, str2, str3;
}

class Value {
    String str1, str2, str3;
}

// later on

Map<Key, Value> map = ...;
map.put(new Key("G", "Merc", "SUV"), new Value("Silver", "400", "100.000"));
map.get(new Key("A4", "Audi", "Sedan"));

Of course, this isn't the only way, but it's the most easily maintainable, and also easiest to modify later on, if say you want to add another property to your keys.

Other ways include using String[] as the key and values, List<String>, and/or Set<String>. You might even roll your own implementation of Map<T>, but again, maintainability is a factor you must consider.

Sign up to request clarification or add additional context in comments.

1 Comment

Just remember that this will not work at all unless you override hashCode and equals
1

If I were going to do this I would just "glue" the keys together with some delimiter and make the key a single string.

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

map.put(key("G", "Merc", "SUV"), new Value("Silver", "400", "100.000"));
map.get(key("A4", "Audi", "Sedan"));

public static String key(String...elements) {
    return String.join("-", elements);
}


1 Comment

In this case better not use dash as delimiter since it is quite common. But I think one gets the idea.
1

Or do a combination of the already suggested answers.

Use a custom class as key and a MultiValueMap for the values.

https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MultiValuedMap.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.