APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.util

public Class TreeMap<K, V>

extends AbstractMap<K, V>
implements NavigableMap<K, V>, Cloneable, Serializable
Class Inheritance
All Implemented Interfaces
java.io.Serializable, java.lang.Cloneable, java.util.NavigableMap, java.util.SortedMap, java.util.SequencedMap, java.util.Map
Type Parameters
<K>
the type of keys maintained by this map
<V>
the type of mapped values
Imports
java.io.Serializable, java.util.function.BiConsumer, .BiFunction, .Consumer, .Function

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest's Introduction to Algorithms.

Note that the ordering maintained by a tree map, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

Note that this implementation is not synchronized. If multiple threads access a map 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 an existing key 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.synchronizedSortedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

  SortedMap m = Collections.synchronizedSortedMap(new TreeMap(...));

The iterators returned by the iterator method of the collections returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own 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 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.

The methods ceilingEntry, firstEntry, floorEntry, higherEntry, lastEntry, lowerEntry, pollFirstEntry, and pollLastEntry return Map.Entry instances that represent snapshots of mappings as of the time of the call. They do not support mutation of the underlying map via the optional setValue method.

The putFirst and putLast methods of this class throw UnsupportedOperationException. The encounter order of mappings is determined by the comparison method; therefore, explicit positioning is not supported.

This class is a member of the Java Collections Framework.

Author
Josh Bloch and Doug Lea
Since
1.2
See Also
Map, HashMap, Hashtable, Comparable, Comparator, Collection

Nested and Inner Type Summary

Modifier and TypeClass and Description
pack-priv static class
pack-priv class
pack-priv static class
pack-priv static class
pack-priv static class
TreeMap.Entry<K, V>

Node in the Tree.

pack-priv class
pack-priv class
pack-priv static class
pack-priv class
pack-priv static class
pack-priv static class
pack-priv abstract class
TreeMap.PrivateEntryIterator<T>

Base class for TreeMap Iterators

private class
TreeMap.SubMap

This class exists solely for the sake of serialization compatibility with previous releases of TreeMap that did not support NavigableMap.

pack-priv static class
TreeMap.TreeMapSpliterator<K, V>

Base class for spliterators.

pack-priv class
pack-priv class
pack-priv static class

Field Summary

Modifier and TypeField and Description
private static final boolean
private final Comparator<? super K>
comparator

The comparator used to maintain order in this tree map, or null if it uses the natural ordering of its keys.

private transient NavigableMap<K, V>
private transient TreeMap<K, V>.EntrySet
entrySet

Fields initialized to contain an instance of the entry set view the first time this view is requested.

private transient int
modCount

The number of structural modifications to the tree.

private static final boolean
private transient TreeMap.Entry<K, V>
private static final long
private transient int
size

The number of entries in the tree

private static final Object
UNBOUNDED

Dummy value serving as unmatchable fence key for unbounded SubMapIterators

Inherited from java.util.AbstractMap:
keySetvalues

Constructor Summary

AccessConstructor and Description
public
TreeMap()

Constructs a new, empty tree map, using the natural ordering of its keys.

public
TreeMap(Comparator<? super K>
the comparator that will be used to order this map. If null, the natural ordering of the keys will be used.
comparator
)

Constructs a new, empty tree map, ordered according to the given comparator.

public
TreeMap(Map<? extends K, ? extends V>
the map whose mappings are to be placed in this map
m
)

Constructs a new tree map containing the same mappings as the given map, ordered according to the natural ordering of its keys.

public
TreeMap(SortedMap<K, ? extends V>
the sorted map whose mappings are to be placed in this map, and whose comparator is to be used to sort this map
m
)

Constructs a new tree map containing the same mappings and using the same ordering as the specified sorted map.

Method Summary

Modifier and TypeMethod and Description
pack-priv void
addAllForTreeSet(SortedSet<? extends K> set, V defaultVal)

Intended to be called only from TreeSet.addAll

private void
addEntry(K key, V value, TreeMap.Entry<K, V> parent, boolean addToLeft)

private void
addEntryToEmptyMap(K key, V value)

private void
buildFromSorted(int
the number of keys (or key-value pairs) to be read from the iterator or stream
size
,
Iterator<?>
If non-null, new entries are created from entries or keys read from this iterator.
it
,
ObjectInputStream
If non-null, new entries are created from keys and possibly values read from this stream in serialized form. Exactly one of it and str should be non-null.
str
,
V
if non-null, this default value is used for each value in the map. If null, each value is read from iterator or stream, as described above.
defaultVal
)

Linear time tree building algorithm from sorted data.

private final TreeMap.Entry<K, V>
buildFromSorted(int
the current level of tree. Initial call should be 0.
level
,
int
the first element index of this subtree. Initial should be 0.
lo
,
int
the last element index of this subtree. Initial should be size-1.
hi
,
int
the level at which nodes should be red. Must be equal to computeRedLevel for tree of this size.
redLevel
,
Iterator<?> it, ObjectInputStream str, V defaultVal)

Recursive "helper method" that does the real work of the previous method.

private V
callMappingFunctionWithCheck(K key, Function<? super K, ? extends V> mappingFunction)

private V
callRemappingFunctionWithCheck(K key, V oldValue, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

public Map.Entry<K, V>
ceilingEntry(K key)

Implements java.util.NavigableMap.ceilingEntry.

Returns a key-value mapping associated with the least key greater than or equal to the given key, or null if there is no such key.

public K
ceilingKey(K key)

Implements java.util.NavigableMap.ceilingKey.

Returns the least key greater than or equal to the given key, or null if there is no such key.

public void
clear()

Overrides java.util.AbstractMap.clear.

Implements java.util.Map.clear.

Removes all of the mappings from this map.

public Object

Returns:

a shallow copy of this map
clone
()

Overrides java.util.AbstractMap.clone.

Returns a shallow copy of this TreeMap instance.

private static <K, V> boolean
colorOf(TreeMap.Entry<K, V> p)

Balancing operations.

public Comparator<? super K>
comparator()

Implements java.util.SortedMap.comparator.

Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.

pack-priv final int
compare(Object k1, Object k2)

Compares two keys using the correct comparison method for this TreeMap.

public V
compute(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Overrides default java.util.Map.compute.

Attempts to compute a mapping for the specified key and its current mapped value, or null if there is no current mapping (optional operation).

public V
computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)

Overrides default java.util.Map.computeIfAbsent.

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 (optional operation).

public V
computeIfPresent(K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

Overrides default java.util.Map.computeIfPresent.

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 (optional operation).

private static int
computeRedLevel(int
the (non-negative) number of keys in the tree to be built
size
)

Finds the level down to which to assign all nodes BLACK.

public boolean

Returns:

true if this map contains a mapping for the specified key
containsKey
(Object
key whose presence in this map is to be tested
key
)

Overrides java.util.AbstractMap.containsKey.

Implements java.util.Map.containsKey.

Returns true if this map contains a mapping for the specified key.

public boolean

Returns:

true if a mapping to value exists; false otherwise
containsValue
(Object
value whose presence in this map is to be tested
value
)

Overrides java.util.AbstractMap.containsValue.

Implements java.util.Map.containsValue.

Returns true if this map maps one or more keys to the specified value.

private void
deleteEntry(TreeMap.Entry<K, V> p)

Delete node p, and then rebalance the tree.

pack-priv Iterator<K>
public NavigableSet<K>
descendingKeySet()

Implements java.util.NavigableMap.descendingKeySet.

Returns a reverse order NavigableSet view of the keys contained in this map.

pack-priv final Spliterator<K>
public NavigableMap<K, V>
descendingMap()

Implements java.util.NavigableMap.descendingMap.

Returns a reverse order view of the mappings contained in this map.

public Set<Map.Entry<K, V>>
entrySet()

Implements abstract java.util.AbstractMap.entrySet.

Implements java.util.SortedMap.entrySet, java.util.Map.entrySet.

Returns a Set view of the mappings contained in this map.

pack-priv static <K, V> Map.Entry<K, V>
exportEntry(TreeMap.Entry<K, V> e)

Return SimpleImmutableEntry for entry, or null if null

public Map.Entry<K, V>
firstEntry()

Implements java.util.NavigableMap.firstEntry.

Returns a key-value mapping associated with the least key in this map, or null if the map is empty.

public K
firstKey()

Implements java.util.SortedMap.firstKey.

Returns the first (lowest) key currently in this map.

private void
fixAfterDeletion(TreeMap.Entry<K, V> x)

From CLR

private void
fixAfterInsertion(TreeMap.Entry<K, V> x)

From CLR

public Map.Entry<K, V>
floorEntry(K key)

Implements java.util.NavigableMap.floorEntry.

Returns a key-value mapping associated with the greatest key less than or equal to the given key, or null if there is no such key.

public K
floorKey(K key)

Implements java.util.NavigableMap.floorKey.

Returns the greatest key less than or equal to the given key, or null if there is no such key.

public void
forEach(BiConsumer<? super K, ? super V> action)

Overrides default java.util.Map.forEach.

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

public V
get(Object key)

Overrides java.util.AbstractMap.get.

Implements java.util.Map.get.

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

pack-priv final TreeMap.Entry<K, V>
getCeilingEntry(K key)

Returns the entry for the least key greater than or equal to the specified key; if no such entry exists (i.e. the specified key is greater than any key in the tree, or the tree is empty), returns null.

pack-priv final TreeMap.Entry<K, V>

Returns:

this map's entry for the given key, or null if the map does not contain an entry for the key
getEntry
(Object key)

Returns this map's entry for the given key, or null if the map does not contain an entry for the key.

pack-priv final TreeMap.Entry<K, V>
getEntryUsingComparator(Object key)

Version of getEntry using comparator.

pack-priv final TreeMap.Entry<K, V>
getFirstEntry()

Returns the first Entry in the TreeMap (according to the TreeMap's key-sort function).

pack-priv final TreeMap.Entry<K, V>
getFloorEntry(K key)

Returns the entry for the greatest key less than or equal to the specified key; if no such entry exists (i.e. the specified key is less than any key in the tree, or the tree is empty), returns null.

pack-priv final TreeMap.Entry<K, V>
getHigherEntry(K key)

Returns the entry for the least key greater than the specified key; if no such entry exists (i.e., the greatest key in the Tree is less than or equal to the specified key), returns null.

pack-priv final TreeMap.Entry<K, V>
getLastEntry()

Returns the last Entry in the TreeMap (according to the TreeMap's key-sort function).

pack-priv final TreeMap.Entry<K, V>
getLowerEntry(K key)

Returns the entry for the greatest key less than the specified key; if no such entry exists (i.e., the least key in the Tree is greater than or equal to the specified key), returns null.

public NavigableMap<K, V>
headMap(K toKey, boolean inclusive)

Implements java.util.NavigableMap.headMap.

Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is true) toKey.

public SortedMap<K, V>
headMap(K toKey)

Implements java.util.NavigableMap.headMap.

Returns a view of the portion of this map whose keys are strictly less than toKey.

public Map.Entry<K, V>
higherEntry(K key)

Implements java.util.NavigableMap.higherEntry.

Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.

public K
higherKey(K key)

Implements java.util.NavigableMap.higherKey.

Returns the least key strictly greater than the given key, or null if there is no such key.

pack-priv static <K> K
key(TreeMap.Entry<K, ?> e)

Returns the key corresponding to the specified Entry.

pack-priv Iterator<K>
pack-priv static <K, V> K
keyOrNull(TreeMap.Entry<K, V> e)

Return key for entry, or null if null

public Set<K>
keySet()

Overrides java.util.AbstractMap.keySet.

Implements java.util.SortedMap.keySet, java.util.Map.keySet.

Returns a Set view of the keys contained in this map.

pack-priv final Spliterator<K>
pack-priv static <K> Spliterator<K>
keySpliteratorFor(NavigableMap<K, ?> m)

Currently, we support Spliterator-based versions only for the full map, in either plain of descending form, otherwise relying on defaults because size estimation for submaps would dominate costs.

public Map.Entry<K, V>
lastEntry()

Implements java.util.NavigableMap.lastEntry.

Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.

public K
lastKey()

Implements java.util.SortedMap.lastKey.

Returns the last (highest) key currently in this map.

private static <K, V> TreeMap.Entry<K, V>
leftOf(TreeMap.Entry<K, V> p)

public Map.Entry<K, V>
lowerEntry(K key)

Implements java.util.NavigableMap.lowerEntry.

Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.

public K
lowerKey(K key)

Implements java.util.NavigableMap.lowerKey.

Returns the greatest key strictly less than the given key, or null if there is no such key.

public V
merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

Overrides default java.util.Map.merge.

If the specified key is not already associated with a value or is associated with null, associates it with the given non-null value (optional operation).

private V
mergeValue(TreeMap.Entry<K, V> t, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction)

private static <K, V> TreeMap.Entry<K, V>
public Map.Entry<K, V>
pollFirstEntry()

Implements java.util.NavigableMap.pollFirstEntry.

Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty (optional operation).

public Map.Entry<K, V>
pollLastEntry()

Implements java.util.NavigableMap.pollLastEntry.

Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty (optional operation).

pack-priv static <K, V> TreeMap.Entry<K, V>
predecessor(TreeMap.Entry<K, V> t)

Returns the predecessor of the specified Entry, or null if no such.

public V

Returns:

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
put
(K
key with which the specified value is to be associated
key
,
V
value to be associated with the specified key
value
)

Overrides java.util.AbstractMap.put.

Implements java.util.Map.put.

Associates the specified value with the specified key in this map.

private V
put(K key, V value, boolean replaceOld)

public void
putAll(Map<? extends K, ? extends V>
mappings to be stored in this map
map
)

Overrides java.util.AbstractMap.putAll.

Implements java.util.Map.putAll.

Copies all of the mappings from the specified map to this map.

public V
putFirst(K k, V v)

Overrides default java.util.SortedMap.putFirst.

Throws UnsupportedOperationException.

public V
putIfAbsent(K key, V value)

Overrides default java.util.Map.putIfAbsent.

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 (optional operation).

public V
putLast(K k, V v)

Overrides default java.util.SortedMap.putLast.

Throws UnsupportedOperationException.

private void
readObject(final ObjectInputStream s)

Reconstitute the TreeMap instance from a stream (i.e., deserialize it).

pack-priv void
readTreeSet(int size, ObjectInputStream s, V defaultVal)

Intended to be called only from TreeSet.readObject

private V
remapValue(TreeMap.Entry<K, V> t, K key, BiFunction<? super K, ? super V, ? extends V> remappingFunction)

public V

Returns:

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key.)
remove
(Object
key for which mapping should be removed
key
)

Overrides java.util.AbstractMap.remove.

Implements java.util.Map.remove.

Removes the mapping for this key from this TreeMap if present.

public boolean
replace(K key, V oldValue, V newValue)

Overrides default java.util.Map.replace.

Replaces the entry for the specified key only if currently mapped to the specified value (optional operation).

public V
replace(K key, V value)

Overrides default java.util.Map.replace.

Replaces the entry for the specified key only if it is currently mapped to some value (optional operation).

public void
replaceAll(BiFunction<? super K, ? super V, ? extends V> function)

Overrides default java.util.Map.replaceAll.

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 (optional operation).

private static <K, V> TreeMap.Entry<K, V>
private void
rotateLeft(TreeMap.Entry<K, V> p)

From CLR

private void
rotateRight(TreeMap.Entry<K, V> p)

From CLR

private static <K, V> void
setColor(TreeMap.Entry<K, V> p, boolean c)

public int

Returns:

the number of key-value mappings in this map
size
()

Overrides java.util.AbstractMap.size.

Implements java.util.Map.size.

Returns the number of key-value mappings in this map.

public NavigableMap<K, V>
subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive)

Implements java.util.NavigableMap.subMap.

Returns a view of the portion of this map whose keys range from fromKey to toKey.

public SortedMap<K, V>
subMap(K fromKey, K toKey)

Implements java.util.NavigableMap.subMap.

Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive.

pack-priv static <K, V> TreeMap.Entry<K, V>
successor(TreeMap.Entry<K, V> t)

Returns the successor of the specified Entry, or null if no such.

public NavigableMap<K, V>
tailMap(K fromKey, boolean inclusive)

Implements java.util.NavigableMap.tailMap.

Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is true) fromKey.

public SortedMap<K, V>
tailMap(K fromKey)

Implements java.util.NavigableMap.tailMap.

Returns a view of the portion of this map whose keys are greater than or equal to fromKey.

pack-priv static final boolean
valEquals(Object o1, Object o2)

Test two values for equality.

public Collection<V>
values()

Overrides java.util.AbstractMap.values.

Implements java.util.SortedMap.values, java.util.Map.values.

Returns a Collection view of the values contained in this map.

private void
writeObject(ObjectOutputStream s)

Save the state of the TreeMap instance to a stream (i.e., serialize it).

Inherited from java.util.AbstractMap:
equalshashCodeisEmptytoString