Wants to create a map with two keys and values as a list. Could you please help me with a sample code for the same
Asked
Active
Viewed 53 times
-2
-
2Possible duplicate of [HashMap with multiple values under the same key](https://stackoverflow.com/questions/4956844/hashmap-with-multiple-values-under-the-same-key) – tobsob Oct 25 '19 at 06:38
-
It is not clear if you want a map with two objects as key or one with two keys, which would mean just two entries... What is it? – deHaar Oct 25 '19 at 06:44
-
two keys == two maps ?? or do you mean a key with two values/fields? – user85421 Oct 25 '19 at 07:23
-
I guess you want something like this: https://stackoverflow.com/questions/14677993/how-to-create-a-hashmap-with-two-keys-key-pair-value – sanastasiadis Oct 25 '19 at 07:31
-
`Map
,V>`? – dan1st Oct 25 '19 at 07:44
1 Answers
1
I think you need something like this:
- Firstly you need a POJO which contains your composite key, and to avoid messing up the KeySet inside the map, that pojo must implements
equals
andhashcode
import java.util.Objects;
public class MyKey {
private final String firstKeyAttr;
private final Integer secondKeyAttr;
public MyKey(String firstKeyAttr, Integer secondKeyAttr) {
this.firstKeyAttr = firstKeyAttr;
this.secondKeyAttr = secondKeyAttr;
}
public String getFirstKeyAttr() {
return firstKeyAttr;
}
public Integer getSecondKeyAttr() {
return secondKeyAttr;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyKey myKey = (MyKey) o;
return Objects.equals(firstKeyAttr, myKey.firstKeyAttr) &&
Objects.equals(secondKeyAttr, myKey.secondKeyAttr);
}
@Override
public int hashCode() {
return Objects.hash(firstKeyAttr, secondKeyAttr);
}
}
- And then, you can create a map in this way:
public static void main(String[] args) {
Map<MyKey, List<Object>> myMap = new HashMap<>();
myMap.put(new MyKey("key1", 1), Collections.singletonList(1));
...
}