[英]Java Map with multiple keys
我需要创建一个包含3列的地图:2个键和1个值。 因此,每个值将包含2个不同类类型的键,并且可以使用任一键来获取。 但是我的问题是HashMap / Map仅支持1个键和1个值。 有没有办法创建Map<Key1, Key2, Value>
类的东西Map<Key1, Key2, Value>
而不是Map<Key, Value>
? 所以Value
可以通过使用其任一中获取Key1
或Key2
。
如果是重复的问题或不好的问题,我深表歉意,但是我在Stack Overflow上找不到类似的问题。
PS:我不想创建2个映射: Map<Key1, Value>
和Map<Key2, Value>
也不创建嵌套映射我正在寻找一个多键表,就像上面的那样。
您可能必须编写类似地图的类的自定义实现才能实现此目的。 我同意上面的@William Price,最简单的实现是简单地封装两个Map实例。 使用Map接口时要小心,因为它们依赖equals()和hashCode()来确定密钥身份,您打算在合同中打破这些身份。
自己编写符合您要求的课程:
import java.util.HashMap;
import java.util.Map;
public class MMap<Key, OtherKey, Value> {
private final Map<Key, Value> map = new HashMap<>();
private final Map<OtherKey, Value> otherMap = new HashMap<>();
public void put(Key key, OtherKey otherKey, Value value) {
if (key != null) { // you can change this, if you want accept null.
map.put(key, value);
}
if (otherKey != null) {
otherMap.put(otherKey, value);
}
}
public Value get(Key key, OtherKey otherKey) {
if (map.containsKey(key) && otherMap.containsKey(otherKey)) {
if (map.get(key).equals(otherMap.get(otherKey))) {
return map.get(key);
} else {
throw new AssertionError("Collision. Implement your logic.");
}
} else if (map.containsKey(key)) {
return map.get(key);
} else if (otherMap.containsKey(otherKey)) {
return otherMap.get(otherKey);
} else {
return null; // or some optional.
}
}
public Value getByKey(Key key) {
return get(key, null);
}
public Value getByOtherKey(OtherKey otherKey) {
return get(null, otherKey);
}
}
您是否研究过Apache Commons Collection多地图界面? https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.1/org/apache/commons/collections/MultiMap.html
看一看可以在您的上下文中使用的番石榴的Table集合
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html
Table<String,String,String> ==> Map<String,Map<String,String>>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.