我经常使用Map在循环中存储值,比如一组与同一类/组相关的对象的set/list,或者我想要递增的AtomicInteger。因此,我经常编写以下类型的代码(假设我不在我的Map中存储null):
/* Example #1 -- aggregation */
Map<K, Set<O>> map = new HashMap<K, Set<O>>();
for (O o : oList) {
K k = o.getK();
Set<O> oSet = map.get(k);
if (oSet == null) {
oSet = new HashSet<O>(o);
map.put(k, oSet);
} else {
oSet.add(o);
}
}
/* Example #2 -- counting */
Map<K, AtomicInteger> map = new HashMap<K, AtomicInteger>();
for (O o : oList) {
K k = o.getK();
AtomicInteger i = map.get(k);
if (i == null) {
i = new AtomicInteger(1);
map.put(k, i);
} else {
i.increment();
}
}
我知道Apache Common collections的
DefaultedMap
可以在缺少值时从工厂/模型对象中实时创建值;但是,为了避免编写2/3行代码的(相对较小的)麻烦,你会依赖于(另一个)外部库。是否有更简单的解决方案(尤其是针对示例#2)?你们开发人员在这种情况下使用/推荐什么?还有其他提供这种“默认映射”的库吗?还是你们自己编写装饰映射?