开发者

A sorted ComputingMap?

How can I construct a SortedMap on top of Guava's computing map (or vice versa)? I want the sorted map keys as well as computing values on-th开发者_Go百科e-fly.


The simplest is probably to use a ConcurrentSkipListMap and the memoizer idiom (see JCiP), rather than relying on the pre-built unsorted types from MapMaker. An example that you could use as a basis is a decorator implementation.


May be you can do something like this.It's not a complete implementation.Just a sample to convey the idea.

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());

    }

}


If you need the thread safety, this could be tricky, but if you don't I'd recommend something close to Emil's suggestion, but using a ForwardingSortedMap rather than extending TreeMap directly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜