K - the type of keys maintained by this safe mapV - the type of mapped valuespublic class SafeMap<K,V> extends Object
Reverse lookups are also possible. Given a value, one can retrieve either the
first key that maps to the value, or, in the case where no such
mapping exists, the default key (which may be null),
or a set of all keys that map to the value, or, in the case
where no such mapping exists, an empty set.
For example, suppose you have two enumerations:
public enum Roman { I, II, III, IV, V, XX }
public enum Greek { ALPHA, BETA, GAMMA }
And you want to create the following mapping:
I --> ALPHA II --> ALPHA III --> ALPHA IV --> BETA V --> GAMMA (default: ALPHA)This is done by employing the
Builder inner-class as an intermediary, as follows:
private static final SafeMap<Roman,Greek> map =
new SafeMap.Builder<Roman,Greek>(Greek.ALPHA)
.add(Roman.I, Greek.ALPHA)
.add(Roman.II, Greek.ALPHA)
.add(Roman.III, Greek.ALPHA)
.add(Roman.IV, Greek.BETA)
.add(Roman.V, Greek.GAMMA)
.build();
Note that the default value is specified as a paramter to the builder constructor
and that all required mappings are added in a chained expression, ending with
the build() call to create the map instance.
Now we can look up values:
map.get(Roman.I); // returns Greek.ALPHA map.get(Roman.IV); // returns Greek.BETA map.get(Roman.XX); // returns Greek.ALPHA map.get(null); // returns Greek.ALPHA map.getFirstKey(Greek.ALPHA) // returns Roman.I map.getAllKeys(Greek.ALPHA) // returns Set<Roman> containing I, II, III
Under the hood, this class uses a TreeMap so that entries are kept sorted by their keys.
Thus, when using getFirstKey(V) one should expect the key that comes earliest in the sort
order (declaration order for enumeration constants).
| Modifier and Type | Class and Description |
|---|---|
static class |
SafeMap.Builder<K,V>
SafeMap builder class.
|
| Modifier and Type | Method and Description |
|---|---|
V |
get(K key)
Returns the value mapped to the given key, or the default value if this
map contains no mapping for the key.
|
Set<K> |
getAllKeys(V value)
Return all keys that are mapped to the given value, or an empty set
if no such mapping exists.
|
K |
getDefaultKey()
Returns the default key for this map.
|
V |
getDefaultValue()
Returns the default value for this map.
|
K |
getFirstKey(V value)
Return the first key that is mapped to the given value, or the default key
if no such mapping exists.
|
int |
size()
Returns the number of elements in the map.
|
String |
toString() |
public V get(K key)
null is specified as the key.key - the keypublic K getFirstKey(V value)
value - the valuepublic Set<K> getAllKeys(V value)
value - the valuepublic V getDefaultValue()
public K getDefaultKey()
public int size()
Copyright © 2014. All Rights Reserved.