如何在Guava 的计算图之上构建一个 SortedMap (反之亦然)?我想要排序的映射键以及即时计算值。
问问题
304 次
3 回答
2
最简单的可能是使用 ConcurrentSkipListMap 和 memoizer idiom(参见 JCiP),而不是依赖 MapMaker 中预先构建的未排序类型。一个可以用作基础的示例是装饰器实现。
于 2010-12-30T19:27:35.500 回答
0
也许你可以做这样的事情。这不是一个完整的实现。只是一个传达这个想法的样本。
public class SortedComputingMap<K, V> extends TreeMap<K, V> {
private Function<K, V> function;
private int maxSize;
public SortedComputingMap(int maxSize, Function<K, V> function) {
this.function = function;
this.maxSize = maxSize;
}
@Override
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
throw new UnsupportedOperationException();
}
@Override
public V get(Object key) {
V tmp = null;
K Key = (K) key;
if ((tmp = super.get(key)) == null) {
super.put(Key, function.apply(Key));
}
if (size() > maxSize)
pollFirstEntry();
return tmp;
}
public static void main(String[] args) {
Map<Integer, Long> sortedMap = new SortedComputingMap<Integer, Long>(3,
new Function<Integer, Long>() {
@Override
public Long apply(Integer n) {
Long fact = 1l;
while (n != 0)
fact *= n--;
return fact;
}
});
sortedMap.get(12);
sortedMap.get(1);
sortedMap.get(2);
sortedMap.get(5);
System.out.println(sortedMap.entrySet());
}
}
于 2010-12-24T06:44:59.270 回答
0
如果您需要线程安全,这可能会很棘手,但如果您不需要,我会推荐一些接近 Emil 建议的东西,但使用 aForwardingSortedMap
而不是TreeMap
直接扩展。
于 2010-12-28T18:49:28.300 回答