Question

One of my favourites from apache commons-collections was the LazyMap which would use a Transformer to instantiate values on the fly when doing map.get(newKey); // Will not return null!.

Why doesn't google collections have the same?

Was it helpful?

Solution

since 10.0, guava have a new class CacheBuilder instead, and it's gwt-compatible.

These are the differences.

OTHER TIPS

Hey look! It does!

It's called new MapMaker().makeComputingMap(Function<? super K, ? extends V> computer)

Awesome.

Note that map maker is a factory - you can make one, set all the object reference types, expansion properties (and even object expiration time!), and then go about creating lots of computing maps (or other types) with one line calls.

e.g. like pretty much everything else about the google-collections library, it's really good - once you've figured out where 'it' is

I suggest to write your own

public class LazyMap<K, V> extends ForwardingMap<K, V> {
    final Function<? super K, ? extends V> factory;
    final Map<K, V> delegate;

    public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
        return new LazyMap<>(map, supplier);
    }

    public static <K, V> LazyMap<K, V> lazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
        return new LazyMap<>(map, factory);
    }

    private LazyMap(final Map<K, V> map, final Function<? super K, ? extends V> factory) {
        this.factory = factory;
        this.delegate = map;
    }

    private LazyMap(final Map<K, V> map, final Supplier<? extends V> supplier) {
        this.factory = Functions.forSupplier(supplier);
        this.delegate = map;
    }

    @Override
    protected Map<K, V> delegate() {
        return delegate;
    }

    @Override
    public V get(final Object key) {
        if (delegate().containsKey(key) == false) {
            @SuppressWarnings("unchecked")
            final K castKey = (K) key;
            final V value = factory.apply(castKey);
            delegate().put(castKey, value);
            return value;
        }
        return delegate().get(key);
    }

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top