可能的重复:
如何实现具有多个键的 Map?
多个键到单值映射 Java
我必须获取的值基于两个传入字符串属性的枚举。我一直将其作为单个值的地图。现在我面临着串联。有没有办法让地图有两个键,这样我
Map.get("attr1","attr2");
就可以返回正确的枚举。或者我只需连接所有可能的值并将其用作键?
我正在寻找非常干净的解决方案(我们不是吗:P)
Possible Duplicate:
How to implement a Map with multiple keys?
Multiple Keys to Single Value Map Java
I have to get the value of an enum based on two incoming string attributes. I have been doing this as map for single values. Now I am faced with making a concatenation. Is there a way to have a map have two keys such that I could
Map.get("attr1","attr2");
and this would return the correct enum. Or will I simply have to concatenate all possible values and use this as the key?
I'm searching for the squeaky clean solution (aren't we all :P)
发布评论
评论(6)
好吧,您可以使用
Map>
。我们经常使用它,因此制作了自己的
Map
实现,它提供两个键并在内部使用 map-of-maps 方法。Well, you could use
Map<String, Map<String, YourEnum>>
.We use this a lot and thus made our own
Map
implementation that provides two keys and internally uses the map-of-maps approach.您可以有一个地图的地图,即,
或者您可以使用 equals 方法定义一个对象,即
You could have a map of maps, i.e.
or you could define a object with an equals method, i.e.
在这种情况下,我将创建一个具有这两个属性的包装类,实现
equals()
并可能实现Comparable
和compareTo
委托给这两个元素的复合键。并使用此类作为地图的键。这就像滚动您自己的
Pair
类。看看这个问题的答案,详细说明了这个问题:Java 中的 C++ Pair 相当于什么?In this case I would make a wrapper class with those two attributes, implement
equals()
and maybe implementComparable
andcompareTo
delegating onto the two elements of the composite key. And use this class as key to the map.It would be like rolling your own
Pair
class. Take a look at this question's answers, that elaborate on the matter: What is the equivalent of the C++ Pair in Java?为什么不创建一个包含两个键的类并将其用作映射键?
例如:
Why not create an class that contains the two keys and use that as the map key?
For example:
与托马斯的方法类似,我们(在我的工作中)有“维度”地图类,它们是多个地图的简单包装器。
保持所有地图彼此同步非常容易,并且无需大量可能复杂的代码即可进行相当快速的搜索。 (但是,这是以增加内存使用为代价的)
Similar to Thomas's approach, we (At my work) have 'Dimensional' map classes that are simple wrappers around several Maps.
It is very easy to keep all the maps in sync with each other and allows for a decently quick search without tons of potentially complex code. (However, this comes at the cost of increased Memory use)
org.apache.commons.collections.map.MultiKeyMap 就是你想要的
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiKeyMap.html
示例
org.apache.commons.collections.map.MultiKeyMap is what you want
http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiKeyMap.html
example