Class TreeMap<K,V>
- All Implemented Interfaces:
Serializable,Cloneable,Map<K,V>,NavigableMap<K,V>,SortedMap<K,V>
public class TreeMap<K,V> extends AbstractMap<K,V> implements SortedMap<K,V>, NavigableMap<K,V>, Cloneable, Serializable
put(K, V) and remove(java.lang.Object) are supported.
This map sorts keys using either a user-supplied comparator or the key's natural order:
- User supplied comparators must be able to compare any pair of keys in
this map. If a user-supplied comparator is in use, it will be returned
by
comparator. - If no user-supplied comparator is supplied, keys will be sorted by
their natural order. Keys must be mutually comparable: they must
implement
ComparableandcompareTo()must be able to compare each key with any other key in this map. In this casecomparatorwill return null.
a and b, a.equals(b) if and only
if compare(a, b) == 0.
When the ordering is not consistent with equals the behavior of this
class is well defined but does not honor the contract specified by Map. Consider a tree map of case-insensitive strings, an ordering that is
not consistent with equals:
TreeMap<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
map.put("a", "android");
// The Map API specifies that the next line should print "null" because
// "a".equals("A") is false and there is no mapping for upper case "A".
// But the case insensitive ordering says compare("a", "A") == 0. TreeMap
// uses only comparators/comparable on keys and so this prints "android".
System.out.println(map.get("A"));
- Since:
- 1.2
- See Also:
- Serialized Form
-
Nested Class Summary
Nested classes/interfaces inherited from class java.util.AbstractMap
AbstractMap.SimpleEntry<K,V>, AbstractMap.SimpleImmutableEntry<K,V> -
Constructor Summary
Constructors Constructor Description TreeMap()Create a natural order, empty tree map whose keys must be mutually comparable and non-null.TreeMap(Comparator<? super K> comparator)Create a tree map ordered bycomparator.TreeMap(Map<? extends K,? extends V> copyFrom)Create a natural order tree map populated with the key/value pairs ofcopyFrom.TreeMap(SortedMap<K,? extends V> copyFrom)Create a tree map with the ordering and key/value pairs ofcopyFrom. -
Method Summary
Modifier and Type Method Description Map.Entry<K,V>ceilingEntry(K key)Returns a key-value mapping associated with the least key greater than or equal to the given key, ornullif there is no such key.KceilingKey(K key)Returns the least key greater than or equal to the given key, ornullif there is no such key.voidclear()Removes all elements from thisMap, leaving it empty.Objectclone()Creates and returns a copy of thisObject.Comparator<? super K>comparator()Returns the comparator used to compare keys in this sorted map, or null if the natural ordering is in use.booleancontainsKey(Object key)Returns whether thisMapcontains the specified key.NavigableSet<K>descendingKeySet()Returns a reverse orderNavigableSetview of the keys contained in this map.NavigableMap<K,V>descendingMap()Returns a reverse order view of the mappings contained in this map.Set<Map.Entry<K,V>>entrySet()Returns aSetcontaining all of the mappings in thisMap.Map.Entry<K,V>firstEntry()Returns a key-value mapping associated with the least key in this map, ornullif the map is empty.KfirstKey()Returns the least key in this sorted map.Map.Entry<K,V>floorEntry(K key)Returns a key-value mapping associated with the greatest key less than or equal to the given key, ornullif there is no such key.KfloorKey(K key)Returns the greatest key less than or equal to the given key, ornullif there is no such key.Vget(Object key)Returns the value of the mapping with the specified key.SortedMap<K,V>headMap(K toExclusive)Returns a sorted map over a range of this sorted map with all keys that are less than the specifiedendKey.NavigableMap<K,V>headMap(K to, boolean inclusive)Returns a view of the portion of this map whose keys are less than (or equal to, ifinclusiveis true)toKey.Map.Entry<K,V>higherEntry(K key)Returns a key-value mapping associated with the least key strictly greater than the given key, ornullif there is no such key.KhigherKey(K key)Returns the least key strictly greater than the given key, ornullif there is no such key.booleanisEmpty()Returns whether this map is empty.Set<K>keySet()Returns a set of the keys contained in thisMap.Map.Entry<K,V>lastEntry()Returns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.KlastKey()Returns the greatest key in this sorted map.Map.Entry<K,V>lowerEntry(K key)Returns a key-value mapping associated with the greatest key strictly less than the given key, ornullif there is no such key.KlowerKey(K key)Returns the greatest key strictly less than the given key, ornullif there is no such key.NavigableSet<K>navigableKeySet()Returns aNavigableSetview of the keys contained in this map.Map.Entry<K,V>pollFirstEntry()Removes and returns a key-value mapping associated with the least key in this map, ornullif the map is empty.Map.Entry<K,V>pollLastEntry()Removes and returns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.Vput(K key, V value)Maps the specified key to the specified value.Vremove(Object key)Removes a mapping with the specified key from thisMap.intsize()Returns the number of mappings in thisMap.NavigableMap<K,V>subMap(K from, boolean fromInclusive, K to, boolean toInclusive)Returns a view of the portion of this map whose keys range fromfromKeytotoKey.SortedMap<K,V>subMap(K fromInclusive, K toExclusive)Returns a sorted map over a range of this sorted map with all keys greater than or equal to the specifiedstartKeyand less than the specifiedendKey.SortedMap<K,V>tailMap(K fromInclusive)Returns a sorted map over a range of this sorted map with all keys that are greater than or equal to the specifiedstartKey.NavigableMap<K,V>tailMap(K from, boolean inclusive)Returns a view of the portion of this map whose keys are greater than (or equal to, ifinclusiveis true)fromKey.Methods inherited from class java.util.AbstractMap
containsValue, equals, hashCode, putAll, toString, values
-
Constructor Details
-
TreeMap
public TreeMap()Create a natural order, empty tree map whose keys must be mutually comparable and non-null. -
TreeMap
Create a natural order tree map populated with the key/value pairs ofcopyFrom. This map's keys must be mutually comparable and non-null.Even if
copyFromis aSortedMap, the constructed map will not usecopyFrom's ordering. This constructor always creates a naturally-ordered map. Because theTreeMapconstructor overloads are ambiguous, prefer to construct a map and populate it in two steps:TreeMap<String, Integer> customOrderedMap = new TreeMap<String, Integer>(copyFrom.comparator()); customOrderedMap.putAll(copyFrom); -
TreeMap
Create a tree map ordered bycomparator. This map's keys may only be null ifcomparatorpermits.- Parameters:
comparator- the comparator to order elements with, ornullto use the natural ordering.
-
TreeMap
Create a tree map with the ordering and key/value pairs ofcopyFrom. This map's keys may only be null if thecopyFrom's ordering permits.The constructed map will always use
copyFrom's ordering. Because theTreeMapconstructor overloads are ambiguous, prefer to construct a map and populate it in two steps:TreeMap<String, Integer> customOrderedMap = new TreeMap<String, Integer>(copyFrom.comparator()); customOrderedMap.putAll(copyFrom);
-
-
Method Details
-
clone
Description copied from class:ObjectCreates and returns a copy of thisObject. The default implementation returns a so-called "shallow" copy: It creates a new instance of the same class and then copies the field values (including object references) from this instance to the new instance. A "deep" copy, in contrast, would also recursively clone nested objects. A subclass that needs to implement this kind of cloning should callsuper.clone()to create the new instance and then create deep copies of the nested, mutable objects.- Overrides:
clonein classAbstractMap<K,V>- Returns:
- a copy of this object.
-
size
public int size()Description copied from class:AbstractMapReturns the number of mappings in thisMap.This implementation returns its entry set's size.
-
isEmpty
public boolean isEmpty()Description copied from class:AbstractMapReturns whether this map is empty.This implementation compares
size()to 0.- Specified by:
isEmptyin interfaceMap<K,V>- Overrides:
isEmptyin classAbstractMap<K,V>- Returns:
trueif this map has no elements,falseotherwise.- See Also:
Map.size()
-
get
Description copied from class:AbstractMapReturns the value of the mapping with the specified key.This implementation iterates its entry set, looking for an entry with a key that
keyequals. -
containsKey
Description copied from class:AbstractMapReturns whether thisMapcontains the specified key.This implementation iterates its key set, looking for a key that
keyequals.- Specified by:
containsKeyin interfaceMap<K,V>- Overrides:
containsKeyin classAbstractMap<K,V>- Parameters:
key- the key to search for.- Returns:
trueif this map contains the specified key,falseotherwise.
-
put
Description copied from class:AbstractMapMaps the specified key to the specified value.This base implementation throws
UnsupportedOperationException. -
clear
public void clear()Description copied from class:AbstractMapRemoves all elements from thisMap, leaving it empty.This implementation calls
entrySet().clear().- Specified by:
clearin interfaceMap<K,V>- Overrides:
clearin classAbstractMap<K,V>- See Also:
Map.isEmpty(),Map.size()
-
remove
Description copied from class:AbstractMapRemoves a mapping with the specified key from thisMap.This implementation iterates its entry set, removing the entry with a key that
keyequals. -
firstEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the least key in this map, ornullif the map is empty.- Specified by:
firstEntryin interfaceNavigableMap<K,V>
-
pollFirstEntry
Description copied from interface:NavigableMapRemoves and returns a key-value mapping associated with the least key in this map, ornullif the map is empty.- Specified by:
pollFirstEntryin interfaceNavigableMap<K,V>- Returns:
- the removed first entry of this map,
or
nullif this map is empty
-
firstKey
Description copied from interface:SortedMapReturns the least key in this sorted map. -
lastEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.- Specified by:
lastEntryin interfaceNavigableMap<K,V>
-
pollLastEntry
Description copied from interface:NavigableMapRemoves and returns a key-value mapping associated with the greatest key in this map, ornullif the map is empty.- Specified by:
pollLastEntryin interfaceNavigableMap<K,V>- Returns:
- the removed last entry of this map,
or
nullif this map is empty
-
lastKey
Description copied from interface:SortedMapReturns the greatest key in this sorted map. -
lowerEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the greatest key strictly less than the given key, ornullif there is no such key.- Specified by:
lowerEntryin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- an entry with the greatest key less than
key, ornullif there is no such key
-
lowerKey
Description copied from interface:NavigableMapReturns the greatest key strictly less than the given key, ornullif there is no such key.- Specified by:
lowerKeyin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- the greatest key less than
key, ornullif there is no such key
-
floorEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the greatest key less than or equal to the given key, ornullif there is no such key.- Specified by:
floorEntryin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- an entry with the greatest key less than or equal to
key, ornullif there is no such key
-
floorKey
Description copied from interface:NavigableMapReturns the greatest key less than or equal to the given key, ornullif there is no such key.- Specified by:
floorKeyin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- the greatest key less than or equal to
key, ornullif there is no such key
-
ceilingEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the least key greater than or equal to the given key, ornullif there is no such key.- Specified by:
ceilingEntryin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- an entry with the least key greater than or equal to
key, ornullif there is no such key
-
ceilingKey
Description copied from interface:NavigableMapReturns the least key greater than or equal to the given key, ornullif there is no such key.- Specified by:
ceilingKeyin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- the least key greater than or equal to
key, ornullif there is no such key
-
higherEntry
Description copied from interface:NavigableMapReturns a key-value mapping associated with the least key strictly greater than the given key, ornullif there is no such key.- Specified by:
higherEntryin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- an entry with the least key greater than
key, ornullif there is no such key
-
higherKey
Description copied from interface:NavigableMapReturns the least key strictly greater than the given key, ornullif there is no such key.- Specified by:
higherKeyin interfaceNavigableMap<K,V>- Parameters:
key- the key- Returns:
- the least key greater than
key, ornullif there is no such key
-
comparator
Description copied from interface:SortedMapReturns the comparator used to compare keys in this sorted map, or null if the natural ordering is in use.- Specified by:
comparatorin interfaceSortedMap<K,V>
-
entrySet
Description copied from interface:MapReturns aSetcontaining all of the mappings in thisMap. Each mapping is an instance ofMap.Entry. As theSetis backed by thisMap, changes in one will be reflected in the other. -
keySet
Description copied from class:AbstractMapReturns a set of the keys contained in thisMap. TheSetis backed by thisMapso changes to one are reflected by the other. TheSetdoes not support adding.This implementation returns a view that calls through this to map. Its iterator transforms this map's entry set iterator to return keys.
-
subMap
Description copied from interface:NavigableMapReturns a view of the portion of this map whose keys range fromfromKeytotoKey. IffromKeyandtoKeyare equal, the returned map is empty unlessfromExclusiveandtoExclusiveare both true. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.The returned map will throw an
IllegalArgumentExceptionon an attempt to insert a key outside of its range, or to construct a submap either of whose endpoints lie outside its range.- Specified by:
subMapin interfaceNavigableMap<K,V>- Parameters:
from- low endpoint of the keys in the returned mapfromInclusive-trueif the low endpoint is to be included in the returned viewto- high endpoint of the keys in the returned maptoInclusive-trueif the high endpoint is to be included in the returned view- Returns:
- a view of the portion of this map whose keys range from
fromKeytotoKey
-
subMap
Description copied from interface:SortedMapReturns a sorted map over a range of this sorted map with all keys greater than or equal to the specifiedstartKeyand less than the specifiedendKey. Changes to the returned sorted map are reflected in this sorted map and vice versa.Note: The returned map will not allow an insertion of a key outside the specified range.
-
headMap
Description copied from interface:NavigableMapReturns a view of the portion of this map whose keys are less than (or equal to, ifinclusiveis true)toKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.The returned map will throw an
IllegalArgumentExceptionon an attempt to insert a key outside its range.- Specified by:
headMapin interfaceNavigableMap<K,V>- Parameters:
to- high endpoint of the keys in the returned mapinclusive-trueif the high endpoint is to be included in the returned view- Returns:
- a view of the portion of this map whose keys are less than
(or equal to, if
inclusiveis true)toKey
-
headMap
Description copied from interface:SortedMapReturns a sorted map over a range of this sorted map with all keys that are less than the specifiedendKey. Changes to the returned sorted map are reflected in this sorted map and vice versa.Note: The returned map will not allow an insertion of a key outside the specified range.
-
tailMap
Description copied from interface:NavigableMapReturns a view of the portion of this map whose keys are greater than (or equal to, ifinclusiveis true)fromKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.The returned map will throw an
IllegalArgumentExceptionon an attempt to insert a key outside its range.- Specified by:
tailMapin interfaceNavigableMap<K,V>- Parameters:
from- low endpoint of the keys in the returned mapinclusive-trueif the low endpoint is to be included in the returned view- Returns:
- a view of the portion of this map whose keys are greater than
(or equal to, if
inclusiveis true)fromKey
-
tailMap
Description copied from interface:SortedMapReturns a sorted map over a range of this sorted map with all keys that are greater than or equal to the specifiedstartKey. Changes to the returned sorted map are reflected in this sorted map and vice versa.Note: The returned map will not allow an insertion of a key outside the specified range.
-
descendingMap
Description copied from interface:NavigableMapReturns a reverse order view of the mappings contained in this map. The descending map is backed by this map, so changes to the map are reflected in the descending map, and vice-versa. If either map is modified while an iteration over a collection view of either map is in progress (except through the iterator's ownremoveoperation), the results of the iteration are undefined.The returned map has an ordering equivalent to
Collections.reverseOrder(comparator()). The expressionm.descendingMap().descendingMap()returns a view ofmessentially equivalent tom.- Specified by:
descendingMapin interfaceNavigableMap<K,V>- Returns:
- a reverse order view of this map
-
descendingKeySet
Description copied from interface:NavigableMapReturns a reverse orderNavigableSetview of the keys contained in this map. The set's iterator returns the keys in descending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's ownremoveoperation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via theIterator.remove,Set.remove,removeAll,retainAll, andclearoperations. It does not support theaddoraddAlloperations.- Specified by:
descendingKeySetin interfaceNavigableMap<K,V>- Returns:
- a reverse order navigable set view of the keys in this map
-