HashMap: One Key, multiple Values
It sounds like you're looking for a multimap. Guava has various Multimap
implementations, usually created via the Multimaps
class.
I would suggest that using that implementation is likely to be simpler than rolling your own, working out what the API should look like, carefully checking for an existing list when adding a value etc. If your situation has a particular aversion to third party libraries it may be worth doing that, but otherwise Guava is a fabulous library which will probably help you with other code too :)
For example:
Map<Object,Pair<Integer,String>> multiMap = new HashMap<Object,Pair<Integer,String>>();
where the Pair
is a parametric class
public class Pair<A, B> {
A first = null;
B second = null;
Pair(A first, B second) {
this.first = first;
this.second = second;
}
public A getFirst() {
return first;
}
public void setFirst(A first) {
this.first = first;
}
public B getSecond() {
return second;
}
public void setSecond(B second) {
this.second = second;
}
}
Libraries exist to do this, but the simplest plain Java way is to create a Map
of List
like this:
Map<Object,ArrayList<Object>> multiMap = new HashMap<>();
This is what i found in a similar question's answer
Map<String, List<String>> hm = new HashMap<String, List<String>>();
List<String> values = new ArrayList<String>();
values.add("Value 1");
values.add("Value 2");
hm.put("Key1", values);
// to get the arraylist
System.out.println(hm.get("key1"));
RESULT: [Value 1, Value 2]