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