Sorting ComputingMap?

How can I build a SortedMap on top of a Guava graphics card (or vice versa)? I want the sorted keys of the card, as well as the computed values ​​on the fly.

+3
source share
3 answers

The simplest is probably the use of ConcurrentSkipListMap and the idiom memoizer (see JCiP), rather than relying on prebuilt unsorted types from MapMaker. An example that you could use as a base is a decorator .

+2
source

, - . . , .

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

    }

}
0

If you need thread safety, it can be tricky, but if you don't, I recommend something close to Emil’s proposal, but using ForwardingSortedMap, rather than expanding TreeMapdirectly.

0
source

Source: https://habr.com/ru/post/1781839/


All Articles