chris01
chris01

Reputation: 12311

Java: Multi Key/Value Map

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?

Upvotes: 0

Views: 476

Answers (3)

Christoph John
Christoph John

Reputation: 3283

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

Upvotes: 1

WJS
WJS

Reputation: 40024

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);
}


Upvotes: 1

Frontear
Frontear

Reputation: 1261

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.

Upvotes: 2

Related Questions