3

我发现自己经常写这样的代码:

Map < String, Set < String > > map = new TreeMap < String, Set < String > >();
String key;
String element;
/* ... */
Set < String > value = map.get(key);
if (value == null) {
  value = new TreeSet < String >();
  map.put(key, value);
}
value.add(element);

我讨厌if上面的陈述——我怎样才能在标准 Java 中摆脱它?如果您可以确认没有标准的 Java 解决方案,那么如果您可以建议一个满足此需求的非标准库,那就太好了。

4

2 回答 2

2

Apache Commons Collections 有一个MultiMap

MultiMap mhm = new MultiHashMap();
mhm.put(key, "A");
mhm.put(key, "B");
mhm.put(key, "C");
Collection coll = (Collection) mhm.get(key);

Guava(以前是 Google Collections)也有一个,它支持泛型,并且有哈希版本:

Multimap<String,String> mhm = new TreeMultimap<String,String>();
// etc.

澄清一下,Multimap<T, S>基本上与 a 相同Map<T, Collection<S>>,并put在需要时自动创建集合。

编辑:更新链接到番石榴,因为显然谷歌收藏已被弃用。

于 2012-04-15T02:58:05.497 回答
1

Hmm... I like Brendan's multimap answer, but you could also use a static utility method and keep to standard java.util classes/interfaces:

public static <K,V> Set<V> getTreeSet(Map<K,Set<V>> map, K key) {
    Set<V> set = map.get(key);
    if (set == null) {
        set = new TreeSet<V>();
        map.put(key, set);
    }
    return set;
}

Then your code with the null checks could be written:

Map < String, Set < String > > map = new TreeMap < String, Set < String > >();
String key;
String element;
/* ... */
MapUtils.getTreeSet(map, key).add(element);

You'd need static method for each collection type, but that seems better than writing the same code over and over again.

于 2012-04-15T04:02:26.223 回答