K
- the type of keys maintained by this mapV
- the type of mapped valuespublic class SmoothieMap<K,V> extends AbstractMap<K,V> implements Cloneable, Serializable
Map
with worst put
latencies more than 100 times
smaller than in ordinary hash table implementations like HashMap
.
SmoothieMap
supports pluggable keys' and values' equivalences, via keysEqual(Object, Object)
, keyHashCode(Object)
and valuesEqual(Object, Object)
, that could be overridden.
Functional additions to the Map
interface, implemented in this class: sizeAsLong()
(SmoothieMap
maximum size is not limited with Java array maximum size,
that is int
-indexed), containsEntry(Object, Object)
, forEachWhile(BiPredicate)
, removeIf(BiPredicate)
.
Note that this implementation is not synchronized. If multiple threads access a
SmoothieMap
concurrently, and at least one of the threads modifies the map structurally,
it must be synchronized externally. (A structural modification is any operation that adds
or deletes one or more mappings; merely changing the value associated with a key that an instance
already contains is not a structural modification.) This is typically accomplished by
synchronizing on some object that naturally encapsulates the map.
If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap
method. This is best done at creation
time, to prevent accidental unsynchronized access to the map:
Map m = Collections.synchronizedMap(new SmoothieMap(...));
SmoothieMap
aims to be as close to HashMap
behaviour and contract as possible,
to give an ability to be used as a drop-in replacement of HashMap
. In particular:
null
keys and values.Serializable
and Cloneable
.remove
method, the iterator will throw a ConcurrentModificationException
. Thus, in the face of concurrent modification, the iterator
fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an
undetermined time in the future.
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally
speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent
modification. Fail-fast iterators (and all bulk operations like forEach(BiConsumer)
,
clear()
, replaceAll(BiFunction)
etc.) throw ConcurrentModificationException
on a best-effort basis. Therefore, it would be wrong to
write a program that depended on this exception for its correctness: the fail-fast
behavior of iterators should be used only to detect bugs.
In terms of performance, favor calling bulk methods like forEach(BiConsumer)
to
iterating the SmoothieMap
via Iterator
, including for-each style iterations on
map's collections views. Especially if you need to remove entries during iteration (i. e. call
Iterator.remove()
) and hash code for key objects is not cached on their side (like it is
cached, for example, in String
class) - try to express your logic using removeIf(BiPredicate)
method in this case.
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V>
Modifier and Type | Field and Description |
---|---|
protected static long |
LONG_PHI_MAGIC
The value for spreading low bits of hash code to high.
|
Constructor and Description |
---|
SmoothieMap()
Creates a new, empty
SmoothieMap . |
SmoothieMap(long expectedSize)
Creates a new, empty
SmoothieMap accommodating the specified number of elements
without the need to dynamically resize. |
SmoothieMap(Map<? extends K,? extends V> m)
Creates a new
SmoothieMap with the same mappings as the given map. |
Modifier and Type | Method and Description |
---|---|
void |
clear()
Removes all of the mappings from this map.
|
SmoothieMap<K,V> |
clone()
Returns a shallow copy of this
SmoothieMap instance: the keys and values themselves
are not cloned. |
V |
compute(K key,
java.util.function.BiFunction<? super K,? super V,? extends V> remappingFunction)
Attempts to compute a mapping for the specified key and its current mapped value (or
null if there is no current mapping). |
V |
computeIfAbsent(K key,
java.util.function.Function<? super K,? extends V> mappingFunction)
If the specified key is not already associated with a value (or is mapped to
null ),
attempts to compute its value using the given mapping function and enters it into this map
unless null . |
V |
computeIfPresent(K key,
java.util.function.BiFunction<? super K,? super V,? extends V> remappingFunction)
If the value for the specified key is present and non-null, attempts to compute a new mapping
given the key and its current mapped value.
|
boolean |
containsEntry(Object key,
Object value)
Returns
true if this map contains a mapping of the given key and value. |
boolean |
containsKey(Object key)
Returns
true if this map contains a mapping for the specified key. |
boolean |
containsValue(Object value)
Returns
true if this map maps one or more keys to the specified value. |
Set<Map.Entry<K,V>> |
entrySet()
Returns a
Set view of the mappings contained in this map. |
void |
forEach(java.util.function.BiConsumer<? super K,? super V> action)
Performs the given action for each entry in this map until all entries have been processed or
the action throws an exception.
|
boolean |
forEachWhile(java.util.function.BiPredicate<? super K,? super V> predicate)
Checks the given
predicate on each entry in this map until all entries have been
processed or the predicate returns false for some entry, or throws an Exception. |
V |
get(Object key)
Returns the value to which the specified key is mapped, or
null if this map contains
no mapping for the key. |
V |
getOrDefault(Object key,
V defaultValue)
Returns the value to which the specified key is mapped, or
defaultValue if this map
contains no mapping for the key. |
boolean |
isEmpty()
Returns
true if this map contains no key-value mappings. |
protected long |
keyHashCode(Object key)
Returns hash code for the given key.
|
protected boolean |
keysEqual(Object queriedKey,
K keyInMap)
Returns
true if the two given key objects should be considered equal for this SmoothieMap . |
Set<K> |
keySet()
Returns a
Set view of the keys contained in this map. |
V |
merge(K key,
V value,
java.util.function.BiFunction<? super V,? super V,? extends V> remappingFunction)
If the specified key is not already associated with a value or is associated with null,
associates it with the given non-null value.
|
V |
put(K key,
V value)
Associates the specified value with the specified key in this map.
|
void |
putAll(Map<? extends K,? extends V> m)
Copies all of the mappings from the specified map to this map.
|
V |
putIfAbsent(K key,
V value)
If the specified key is not already associated with a value (or is mapped to
null )
associates it with the given value and returns null , else returns the current value. |
V |
remove(Object key)
Removes the mapping for a key from this map if it is present.
|
boolean |
remove(Object key,
Object value)
Removes the entry for the specified key only if it is currently mapped to the specified
value.
|
boolean |
removeIf(java.util.function.BiPredicate<? super K,? super V> filter)
Removes all of the entries of this map that satisfy the given predicate.
|
V |
replace(K key,
V value)
Replaces the entry for the specified key only if it is currently mapped to some value.
|
boolean |
replace(K key,
V oldValue,
V newValue)
Replaces the entry for the specified key only if currently mapped to the specified value.
|
void |
replaceAll(java.util.function.BiFunction<? super K,? super V,? extends V> function)
Replaces each entry's value with the result of invoking the given function on that entry
until all entries have been processed or the function throws an exception.
|
int |
size()
Returns the number of key-value mappings in this map.
|
long |
sizeAsLong()
Returns the number of entries in the map, as a
long value (not truncated to Integer.MAX_VALUE , if the map size exceeds it, as returned by size() method). |
Collection<V> |
values()
Returns a
Collection view of the values contained in this map. |
protected boolean |
valuesEqual(Object queriedValue,
V valueInMap)
Returns
true if the two given value objects should be considered equal for this map. |
equals, hashCode, toString
protected static final long LONG_PHI_MAGIC
round(2 ^ 64 * (sqrt(5) - 1))
, Java form of 11400714819323198485.keyHashCode(Object)
,
Constant Field Valuespublic SmoothieMap()
SmoothieMap
.public SmoothieMap(long expectedSize)
SmoothieMap
accommodating the specified number of elements
without the need to dynamically resize.expectedSize
- The implementation performs internal
sizing to accommodate this many elements.IllegalArgumentException
- if the given expectedSize
is negative or too largeprotected boolean keysEqual(@NotNull Object queriedKey, @Nullable K keyInMap)
true
if the two given key objects should be considered equal for this SmoothieMap
.
This method should obey general equivalence relation rules (see Object.equals(Object)
documentation for details), and also should be consistent with keyHashCode(Object)
method in this class (i. e. these methods should overridden together).
It is guaranteed that the first specified key is non-null and the arguments are not
identical (!=), in particular this means that to get IdentityHashMap
behaviour it's
OK to override this method just returning false
:
class IdentitySmoothieMap<K, V> extends SmoothieMap<K, V> {
@Override
protected boolean keysEqual(@NotNull Object queriedKey, @Nullable K keyInMap) {
return false;
}
@Override
protected long keyHashCode(@Nullable Object key) {
return System.identityHashCode(key) * LONG_PHI_MAGIC;
}
}
This method accepts raw Object
argument, because Map
interface allows
to check presence of raw key, e. g. get(Object)
without ClassCastException
.
If you want to subclass parameterized SmoothieMap
, you should cast the arguments to
the key parameter class yourself, e. g.:
class DomainToIpMap extends SmoothieMap<String, Integer> {
@Override
protected boolean keysEqual(@NotNull Object queriedDomain,
@Nullable String domainInMap) {
return ((String) queriedDomain).equalsIgnoreCase(domainInMap));
}
@Override
protected long keyHashCode(@Nullable Object domain) {
return LongHashFunction.xx_r39().hashChars(((String) domain).toLowerCase());
}
}
Default implementation is queriedKey.equals(keyInMap)
.
queriedKey
- the first key to compare, that is passed to queries like get(java.lang.Object)
,
but might also be a key, that is already stored in the mapkeyInMap
- the second key to compare, guaranteed that this key is already stored
in the maptrue
if the given keys should be considered equal for this map, false
otherwisekeyHashCode(Object)
protected long keyHashCode(@Nullable Object key)
This method should obey general hash code contract (see Object.hashCode()
documentation for details), also should be consistent with keysEqual(Object, Object)
method in this class (i. e. these methods should overridden together).
The returned hash codes MUST be distributed well in the whole long
range,
because SmoothieMap
implementation uses high bits of the returned value. When
overriding this method, if you are not sure that you hash codes are distributed well it is
recommended to multiply by LONG_PHI_MAGIC
finally, to spread low bits of the values
to the high.
The default implementation is key != null ? key.hashCode() * LONG_PHI_MAGIC : 0L
.
Note that unlike keysEqual()
method this one receives a Nullable
argument.
If you want to protect yourself from putting null
into SmoothieMap
occasionally, you could skip null
checks in this method:
class NonNullKeysSmoothieMap<K, V> extends SmoothieMap<K, V> {
@Override
protected long keyHashCode(Object key) {
// throws NullPointerException if the key is null
return key.hashCode() * LONG_PHI_MAGIC;
}
}
See other examples of this method override in the documentation to keysEqual(Object, Object)
method.
key
- the key (queried or already stored in the map) to compute hash code forkeysEqual(Object, Object)
protected boolean valuesEqual(@NotNull Object queriedValue, @Nullable V valueInMap)
true
if the two given value objects should be considered equal for this map.
This equivalence is used in the implementations of containsValue(Object)
, containsEntry(Object, Object)
, remove(Object, Object)
, replace(Object,
Object, Object)
methods, and the methods of the values collection.
This method should obey general equivalence relation rules (see Object.equals(Object)
documentation for details).
It is guaranteed that the first specified value is non-null and the arguments are not identical (!=).
This method accepts raw Object
argument, because Map
interface allows
to check presence of raw value, e. g. containsValue(Object)
without ClassCastException
. If you want to subclass parameterized SmoothieMap
, you should
cast the arguments to the value parameter class yourself, e. g.:
class IpToDomainMap extends SmoothieMap<Integer, String> {
@Override
protected boolean valuesEqual(@NotNull Object d1, @Nullable String d2) {
return ((String) d1).equalsIgnoreCase(d2);
}
}
Default implementation is queriedValue.equals(valueInMap)
.
queriedValue
- the first value to compare, that is passed to queries like containsValue(Object)
valueInMap
- the second value to compare, this value is already stored in the maptrue
if the given values should be considered equal for this mappublic final int size()
Integer.MAX_VALUE
elements, returns Integer.MAX_VALUE
.public final long sizeAsLong()
long
value (not truncated to Integer.MAX_VALUE
, if the map size exceeds it, as returned by size()
method).size()
public final boolean isEmpty()
true
if this map contains no key-value mappings.public final boolean containsKey(Object key)
true
if this map contains a mapping for the specified key. More formally,
returns true
if and only if this map contains a mapping for a key k
such that
keysEqual(key, k)
== true
. (There can be at most
one such mapping.)containsKey
in interface Map<K,V>
containsKey
in class AbstractMap<K,V>
key
- key whose presence in this map is to be testedtrue
if this map contains a mapping for the specified keypublic final boolean containsEntry(Object key, Object value)
true
if this map contains a mapping of the given key and value. More
formally, this map should contain a mapping from a key k
to a value v
such
that keysEqual(key, k)
== true
and valuesEqual(value, v)
== true
. (There can be at most one
such mapping.)key
- the key of the mapping to check presence ofvalue
- the value of the mapping to check presence oftrue
if this map contains the specified mapping, false
otherwisepublic final V get(Object key)
null
if this map contains
no mapping for the key.
More formally, if this map contains a mapping from a key k
to a value v
such that keysEqual(key, k)
== true
, then this
method returns v
; otherwise it returns null
. (There can be at most one such
mapping.)
A return value of null
does not necessarily indicate that the map contains
no mapping for the key; it's also possible that the map explicitly maps the key to null
. The containsKey
operation may be used to distinguish these two
cases.
public final V getOrDefault(Object key, V defaultValue)
defaultValue
if this map
contains no mapping for the key.getOrDefault
in interface Map<K,V>
key
- the key whose associated value is to be returneddefaultValue
- the default mapping of the keydefaultValue
if this map
contains no mapping for the keypublic final V replace(K key, V value)
replace
in interface Map<K,V>
key
- key with which the specified value is associatedvalue
- value to be associated with the specified keynull
if there was no
mapping for the key. (A null
return can also indicate that the map previously
associated null
with the key.)public final boolean replace(K key, V oldValue, V newValue)
valuesEqual(Object, Object)
method.public final V put(K key, V value)
m
is said to contain a mapping for a key k
if and only if m.containsKey(k)
would return true
.)put
in interface Map<K,V>
put
in class AbstractMap<K,V>
key
- key with which the specified value is to be associatedvalue
- value to be associated with the specified keykey
, or null
if there was no
mapping for key
. (A null
return can also indicate that the map previously
associated null
with key
.)public final V putIfAbsent(K key, V value)
null
)
associates it with the given value and returns null
, else returns the current value.putIfAbsent
in interface Map<K,V>
key
- key with which the specified value is to be associatedvalue
- value to be associated with the specified keynull
if there was no
mapping for the key. (A null
return can also indicate that the map previously
associated null
with the key.)public final V remove(Object key)
k
to value v
such that keysEqual(key, k)
== true
, that mapping is removed. (The map can contain at
most one such mapping.)
Returns the value to which this map previously associated the key, or null
if the
map contained no mapping for the key.
A return value of null
does not necessarily indicate that the map contained
no mapping for the key; it's also possible that the map explicitly mapped the key to
null
.
The map will not contain a mapping for the specified key once the call returns.
public final boolean remove(Object key, Object value)
valuesEqual(Object, Object)
method.public final V computeIfAbsent(K key, java.util.function.Function<? super K,? extends V> mappingFunction)
null
),
attempts to compute its value using the given mapping function and enters it into this map
unless null
.
If the function returns null
no mapping is recorded. If the function itself throws
an (unchecked) exception, the exception is rethrown, and no mapping is recorded. The most
common usage is to construct a new object serving as an initial mapped value or memoized
result, as in:
map.computeIfAbsent(key, k -> new Value(f(k)));
Or to implement a multi-value map, Map<K,Collection<V>>
,
supporting multiple values per key:
map.computeIfAbsent(key, k -> new HashSet<V>()).add(v);
computeIfAbsent
in interface Map<K,V>
key
- key with which the specified value is to be associatedmappingFunction
- the function to compute a valueNullPointerException
- if the mappingFunction is nullpublic final V computeIfPresent(K key, java.util.function.BiFunction<? super K,? super V,? extends V> remappingFunction)
If the function returns null
, the mapping is removed. If the function itself
throws an (unchecked) exception, the exception is rethrown, and the current mapping is left
unchanged.
computeIfPresent
in interface Map<K,V>
key
- key with which the specified value is to be associatedremappingFunction
- the function to compute a valueNullPointerException
- if the remappingFunction is nullpublic final V compute(K key, java.util.function.BiFunction<? super K,? super V,? extends V> remappingFunction)
null
if there is no current mapping). For example, to either create or append a String
msg to a value mapping:
map.compute(key, (k, v) -> (v == null) ? msg : v.concat(msg))
(Method merge()
is often simpler to use for such purposes.)
If the function returns null
, the mapping is removed (or remains absent if
initially absent). If the function itself throws an (unchecked) exception, the exception is
rethrown, and the current mapping is left unchanged.
compute
in interface Map<K,V>
key
- key with which the specified value is to be associatedremappingFunction
- the function to compute a valueNullPointerException
- if the remappingFunction is nullpublic final V merge(K key, V value, java.util.function.BiFunction<? super V,? super V,? extends V> remappingFunction)
null
. This
method may be of use when combining multiple mapped values for a key. For example, to either
create or append a String msg
to a value mapping:
map.merge(key, msg, String::concat)
If the function returns null
the mapping is removed. If the function itself throws
an (unchecked) exception, the exception is rethrown, and the current mapping is left
unchanged.
merge
in interface Map<K,V>
key
- key with which the resulting value is to be associatedvalue
- the non-null value to be merged with the existing value
associated with the key or, if no existing value or a null value
is associated with the key, to be associated with the keyremappingFunction
- the function to recompute a value if presentNullPointerException
- if remappingFunction is nullpublic final void forEach(java.util.function.BiConsumer<? super K,? super V> action)
forEach
in interface Map<K,V>
action
- The action to be performed for each entryNullPointerException
- if the specified action is nullConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during iterationforEachWhile(BiPredicate)
public final boolean forEachWhile(java.util.function.BiPredicate<? super K,? super V> predicate)
predicate
on each entry in this map until all entries have been
processed or the predicate returns false for some entry, or throws an Exception. Exceptions
thrown by the predicate are relayed to the caller.
The entries will be processed in the same order as the entry set iterator, and forEach(BiConsumer)
order.
If the map is empty, this method returns true
immediately.
predicate
- the predicate to be checked for each entrytrue
if the predicate returned true
for all entries of the map,
false
if it returned false
for some entryNullPointerException
- if the given predicate
is null
ConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during iterationforEach(BiConsumer)
public final void replaceAll(java.util.function.BiFunction<? super K,? super V,? extends V> function)
replaceAll
in interface Map<K,V>
function
- the function to apply to each entryNullPointerException
- if the specified function is nullConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during iterationpublic final boolean containsValue(Object value)
true
if this map maps one or more keys to the specified value. More formally,
returns true
if and only if this map contains at least one mapping to a value v
such that valuesEqual(value, v)
== true
. This operation
requires time linear in the map size.containsValue
in interface Map<K,V>
containsValue
in class AbstractMap<K,V>
value
- value whose presence in this map is to be testedtrue
if this map maps one or more keys to the specified valuepublic final SmoothieMap<K,V> clone()
SmoothieMap
instance: the keys and values themselves
are not cloned.clone
in class AbstractMap<K,V>
ConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during operationpublic final void putAll(Map<? extends K,? extends V> m)
put(k, v)
on this map once for each
mapping from key k
to value v
in the specified map. The behavior of this
operation is undefined if the specified map is modified while the operation is in progress.putAll
in interface Map<K,V>
putAll
in class AbstractMap<K,V>
m
- mappings to be stored in this mapNullPointerException
- if the specified map is nullpublic final void clear()
clear
in interface Map<K,V>
clear
in class AbstractMap<K,V>
ConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during operationpublic final boolean removeIf(java.util.function.BiPredicate<? super K,? super V> filter)
Note the order in which this method visits entries is different from the iteration
and forEach(BiConsumer)
order.
filter
- a predicate which returns true
for entries to be removedtrue
if any entries were removedNullPointerException
- if the specified filter
is null
ConcurrentModificationException
- if any structural modification of the map (new entry
insertion or an entry removal) is detected during iteration@NotNull public final Set<K> keySet()
Set
view of the keys contained in this map. The set is backed by the map,
so changes to the map are reflected in the set, and vice-versa.
If a structural modification of the map (new entry insertion or an entry removal) is
detected while an iteration over the set is in progress (except through the iterator's own
remove
operation), ConcurrentModificationException
is thrown.
The set supports element removal, which removes the corresponding mapping from the map,
via the Iterator.remove
, Set.remove
, removeAll
, retainAll
,
and clear
operations. These operations and queries (contains()
, containsAll()
) respect key equivalence possibly overridden by keyHashCode(Object)
and keysEqual(Object, Object)
methods, but set's own hashCode()
use built-in
Java object hash code for the key objects.
The key set does not support the add
or addAll
operations.
The set is created the first time this method is called, and returned in response to all subsequent calls. No synchronization is performed, so there is a slight chance that multiple calls to this method will not all return the same set.
@NotNull public final Collection<V> values()
Collection
view of the values contained in this map. The collection is
backed by the map, so changes to the map are reflected in the collection, and vice-versa.
If a structural modification of the map (new entry insertion or an entry removal) is
detected while an iteration over the collection is in progress (except through the iterator's
own remove
operation), ConcurrentModificationException
is thrown.
The collection supports element removal, which removes the corresponding mapping from the
map, via the Iterator.remove
, Collection.remove
, removeAll
, retainAll
and clear
operations. These operations and queries (contains()
,
containsAll()
) respect value equivalence possibly overridden by valuesEqual(Object, Object)
method.
The values collection does not support the add
or addAll
operations.
The collection is created the first time this method is called, and returned in response to all subsequent calls. No synchronization is performed, so there is a slight chance that multiple calls to this method will not all return the same collection.
@NotNull public final Set<Map.Entry<K,V>> entrySet()
Set
view of the mappings contained in this map. The set is backed by the
map, so changes to the map are reflected in the set, and vice-versa.
If a structural modification of the map (new entry insertion or an entry removal) is
detected while an iteration over the set is in progress (except through the iterator's own
remove
operation), ConcurrentModificationException
is thrown.
The set supports element removal, which removes the corresponding mapping from the map,
via the Iterator.remove
, Set.remove
, removeAll
, retainAll
and
clear
operations. These operations respect custom key and value equivalences possibly
overridden by keyHashCode(Object)
, keysEqual(Object, Object)
and valuesEqual(Object, Object)
methods, but set's own hashCode()
and hashCode()
and equals()
implementations for the entries, returned by the entry set, use
built-in Java equals()
and hashCode()
implementations for the map's keys and
values.
The entry set does not support the add
or addAll
operations.
The set is created the first time this method is called, and returned in response to all subsequent calls. No synchronization is performed, so there is a slight chance that multiple calls to this method will not all return the same set.
Copyright © 2015–2016. All rights reserved.