|
| 1 | +package org.baeldung.guava; |
| 2 | + |
| 3 | +import java.util.AbstractMap; |
| 4 | +import java.util.AbstractSet; |
| 5 | +import java.util.Iterator; |
| 6 | +import java.util.Map; |
| 7 | +import java.util.Set; |
| 8 | +import java.util.WeakHashMap; |
| 9 | + |
| 10 | +import com.google.common.base.Function; |
| 11 | + |
| 12 | +public class GuavaMapFromSet<K, V> extends AbstractMap<K, V> { |
| 13 | + |
| 14 | + private class SingleEntry implements Entry<K, V> { |
| 15 | + private K key; |
| 16 | + |
| 17 | + public SingleEntry(K key) { |
| 18 | + this.key = key; |
| 19 | + } |
| 20 | + |
| 21 | + @Override |
| 22 | + public K getKey() { |
| 23 | + return this.key; |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public V getValue() { |
| 28 | + V value = GuavaMapFromSet.this.cache.get(this.key); |
| 29 | + if (value == null) { |
| 30 | + value = GuavaMapFromSet.this.function.apply(this.key); |
| 31 | + GuavaMapFromSet.this.cache.put(this.key, value); |
| 32 | + } |
| 33 | + return value; |
| 34 | + } |
| 35 | + |
| 36 | + @Override |
| 37 | + public V setValue(V value) { |
| 38 | + throw new UnsupportedOperationException(); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private class MyEntrySet extends AbstractSet<Entry<K, V>> { |
| 43 | + |
| 44 | + public class EntryIterator implements Iterator<Entry<K, V>> { |
| 45 | + private Iterator<K> inner; |
| 46 | + |
| 47 | + public EntryIterator() { |
| 48 | + this.inner = MyEntrySet.this.keys.iterator(); |
| 49 | + } |
| 50 | + |
| 51 | + @Override |
| 52 | + public boolean hasNext() { |
| 53 | + return this.inner.hasNext(); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public Map.Entry<K, V> next() { |
| 58 | + K key = this.inner.next(); |
| 59 | + return new SingleEntry(key); |
| 60 | + } |
| 61 | + |
| 62 | + @Override |
| 63 | + public void remove() { |
| 64 | + throw new UnsupportedOperationException(); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private Set<K> keys; |
| 69 | + |
| 70 | + public MyEntrySet(Set<K> keys) { |
| 71 | + this.keys = keys; |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + public Iterator<Map.Entry<K, V>> iterator() { |
| 76 | + return new EntryIterator(); |
| 77 | + } |
| 78 | + |
| 79 | + @Override |
| 80 | + public int size() { |
| 81 | + return this.keys.size(); |
| 82 | + } |
| 83 | + |
| 84 | + } |
| 85 | + |
| 86 | + private WeakHashMap<K, V> cache; |
| 87 | + private Set<Entry<K, V>> entries; |
| 88 | + private Function<? super K, ? extends V> function; |
| 89 | + |
| 90 | + public GuavaMapFromSet(Set<K> keys, Function<? super K, ? extends V> function) { |
| 91 | + this.function = function; |
| 92 | + this.cache = new WeakHashMap<K, V>(); |
| 93 | + this.entries = new MyEntrySet(keys); |
| 94 | + } |
| 95 | + |
| 96 | + @Override |
| 97 | + public Set<Map.Entry<K, V>> entrySet() { |
| 98 | + return this.entries; |
| 99 | + } |
| 100 | + |
| 101 | +} |
0 commit comments