开发者

A map with two keys [duplicate]

This question already has answers here: Closed 11 years ago.

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 sear开发者_运维问答ching for the squeaky clean solution (aren't we all :P)


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.


You could have a map of maps, i.e.

Map.get("attr1").get("attr2");

or you could define a object with an equals method, i.e.

Map.get(new MyObject("attr1", "attr2"));


In this case I would make a wrapper class with those two attributes, implement equals() and maybe implement Comparable and compareTo 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:

public class BiKey implements comparable<BiKey>
{
  private String key1;
  private String key2;

  // getters and setters

  // equals and hash code.

  // implement comparable.
}

Map <BiKey, Blammy> blammyMap; // Blammy is the value type.


Similar to Thomas's approach, we (At my work) have 'Dimensional' map classes that are simple wrappers around several Maps.

public class MultiKeyMap {
  private HashMap<keyOne, Object> keyOneToObjectMap;
  private HashMap<keyTwo, Object> keyTwoToObjectMap;
  ...etc


}

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 is what you want

http://commons.apache.org/collections/apidocs/org/apache/commons/collections/map/MultiKeyMap.html

example

 private MultiKeyMap cache = MultiKeyMap.decorate(new LRUMap(50));

 public String getAirlineName(String code, String locale) {
   String name = (String) cache.get(code, locale);
   if (name == null) {
     name = getAirlineNameFromDB(code, locale);
     cache.put(code, locale, name);
   }
   return name;
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜