A collection similar to a Map, but which may associate multiple values with a single key. If you call put(K, V) twice, with the same key but different values, the multimap contains mappings from the key to both values.
public class DefaultMap<K, V> extends ForwardingMap<K, V> {
private final Map<K, V> delegate;
private final Supplier<V> defaultSupplier;
/**
* Creates a map which uses the given value as the default for <i>all</i>
* keys. You should only use immutable values as a shared default key.
* Prefer {@link #create(Supplier)} to construct a new instance for each key.
*/
public static DefaultMap<K, V> create(V defaultValue) {
return create(() -> defaultValue);
}
public static DefaultMap<K, V> create(Supplier<V> defaultSupplier) {
return new DefaultMap<>(new HashMap<>(), defaultSupplier);
}
public DefaultMap<K, V>(Map<K, V> delegate, Supplier<V> defaultSupplier) {
this.delegate = Objects.requireNonNull(delegate);
this.defaultSupplier = Objects.requireNonNull(defaultSupplier);
}
@Override
public V get(K key) {
return delegate().computeIfAbsent(key, k -> defaultSupplier.get());
}
}
除了apache集合之外,还要检查google collections:
没有什么能让默认dict的行为开箱即用。然而,用Java创建自己的默认dict并不是那么困难。
这个类可以如下使用:
此代码将打印:
{1=[2, 3]}
在大多数需要
defaultdict
的情况下,使用设计正确的Multimap或Multiset会让您更加高兴,这正是您真正需要的。多重映射是键->;集合映射(默认为空集合),多重集是键->;整数映射(默认为零)。Guava提供了非常好的Multimaps and Multisets实现,几乎涵盖了所有用例。
但是(这就是为什么我发布了一个新的答案)使用Java 8,您现在可以用任何现有的
Map
复制defaultdict
的剩余用例。如果要封装这些调用,可以使用番石榴的^{} :
然后像这样构造默认映射:
相关问题 更多 >
编程相关推荐