Package java.util

Class TreeMap<K,​V>

java.lang.Object
java.util.AbstractMap<K,​V>
java.util.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
A map whose entries are sorted by their keys. All optional operations such as 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 Comparable and compareTo() must be able to compare each key with any other key in this map. In this case comparator will return null.
With either a comparator or a natural ordering, comparisons should be consistent with equals. An ordering is consistent with equals if for every pair of keys 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>

    Nested classes/interfaces inherited from interface java.util.Map

    Map.Entry<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 by comparator.
    TreeMap​(Map<? extends K,​? extends V> copyFrom)
    Create a natural order tree map populated with the key/value pairs of copyFrom.
    TreeMap​(SortedMap<K,​? extends V> copyFrom)
    Create a tree map with the ordering and key/value pairs of copyFrom.
  • 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, or null if there is no such key.
    K ceilingKey​(K key)
    Returns the least key greater than or equal to the given key, or null if there is no such key.
    void clear()
    Removes all elements from this Map, leaving it empty.
    Object clone()
    Creates and returns a copy of this Object.
    Comparator<? super K> comparator()
    Returns the comparator used to compare keys in this sorted map, or null if the natural ordering is in use.
    boolean containsKey​(Object key)
    Returns whether this Map contains the specified key.
    NavigableSet<K> descendingKeySet()
    Returns a reverse order NavigableSet view 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 a Set containing all of the mappings in this Map.
    Map.Entry<K,​V> firstEntry()
    Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
    K firstKey()
    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, or null if there is no such key.
    K floorKey​(K key)
    Returns the greatest key less than or equal to the given key, or null if there is no such key.
    V get​(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 specified endKey.
    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, if inclusive is 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, or null if there is no such key.
    K higherKey​(K key)
    Returns the least key strictly greater than the given key, or null if there is no such key.
    boolean isEmpty()
    Returns whether this map is empty.
    Set<K> keySet()
    Returns a set of the keys contained in this Map.
    Map.Entry<K,​V> lastEntry()
    Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
    K lastKey()
    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, or null if there is no such key.
    K lowerKey​(K key)
    Returns the greatest key strictly less than the given key, or null if there is no such key.
    NavigableSet<K> navigableKeySet()
    Returns a NavigableSet view 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, or null if the map is empty.
    Map.Entry<K,​V> pollLastEntry()
    Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
    V put​(K key, V value)
    Maps the specified key to the specified value.
    V remove​(Object key)
    Removes a mapping with the specified key from this Map.
    int size()
    Returns the number of mappings in this Map.
    NavigableMap<K,​V> subMap​(K from, boolean fromInclusive, K to, boolean toInclusive)
    Returns a view of the portion of this map whose keys range from fromKey to toKey.
    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 specified startKey and less than the specified endKey.
    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 specified startKey.
    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, if inclusive is true) fromKey.

    Methods inherited from class java.util.AbstractMap

    containsValue, equals, hashCode, putAll, toString, values

    Methods inherited from class java.lang.Object

    finalize, getClass, notify, notifyAll, wait, wait, wait

    Methods inherited from interface java.util.Map

    containsValue, equals, hashCode, putAll, values
  • Constructor Details

    • TreeMap

      public TreeMap()
      Create a natural order, empty tree map whose keys must be mutually comparable and non-null.
    • TreeMap

      public TreeMap​(Map<? extends K,​? extends V> copyFrom)
      Create a natural order tree map populated with the key/value pairs of copyFrom. This map's keys must be mutually comparable and non-null.

      Even if copyFrom is a SortedMap, the constructed map will not use copyFrom's ordering. This constructor always creates a naturally-ordered map. Because the TreeMap constructor 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

      public TreeMap​(Comparator<? super K> comparator)
      Create a tree map ordered by comparator. This map's keys may only be null if comparator permits.
      Parameters:
      comparator - the comparator to order elements with, or null to use the natural ordering.
    • TreeMap

      public TreeMap​(SortedMap<K,​? extends V> copyFrom)
      Create a tree map with the ordering and key/value pairs of copyFrom. This map's keys may only be null if the copyFrom's ordering permits.

      The constructed map will always use copyFrom's ordering. Because the TreeMap constructor 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

      public Object clone()
      Description copied from class: Object
      Creates and returns a copy of this Object. 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 call super.clone() to create the new instance and then create deep copies of the nested, mutable objects.
      Overrides:
      clone in class AbstractMap<K,​V>
      Returns:
      a copy of this object.
    • size

      public int size()
      Description copied from class: AbstractMap
      Returns the number of mappings in this Map.

      This implementation returns its entry set's size.

      Specified by:
      size in interface Map<K,​V>
      Overrides:
      size in class AbstractMap<K,​V>
      Returns:
      the number of mappings in this Map.
    • isEmpty

      public boolean isEmpty()
      Description copied from class: AbstractMap
      Returns whether this map is empty.

      This implementation compares size() to 0.

      Specified by:
      isEmpty in interface Map<K,​V>
      Overrides:
      isEmpty in class AbstractMap<K,​V>
      Returns:
      true if this map has no elements, false otherwise.
      See Also:
      Map.size()
    • get

      public V get​(Object key)
      Description copied from class: AbstractMap
      Returns the value of the mapping with the specified key.

      This implementation iterates its entry set, looking for an entry with a key that key equals.

      Specified by:
      get in interface Map<K,​V>
      Overrides:
      get in class AbstractMap<K,​V>
      Parameters:
      key - the key.
      Returns:
      the value of the mapping with the specified key, or null if no mapping for the specified key is found.
    • containsKey

      public boolean containsKey​(Object key)
      Description copied from class: AbstractMap
      Returns whether this Map contains the specified key.

      This implementation iterates its key set, looking for a key that key equals.

      Specified by:
      containsKey in interface Map<K,​V>
      Overrides:
      containsKey in class AbstractMap<K,​V>
      Parameters:
      key - the key to search for.
      Returns:
      true if this map contains the specified key, false otherwise.
    • put

      public V put​(K key, V value)
      Description copied from class: AbstractMap
      Maps the specified key to the specified value.

      This base implementation throws UnsupportedOperationException.

      Specified by:
      put in interface Map<K,​V>
      Overrides:
      put in class AbstractMap<K,​V>
      Parameters:
      key - the key.
      value - the value.
      Returns:
      the value of any previous mapping with the specified key or null if there was no mapping.
    • clear

      public void clear()
      Description copied from class: AbstractMap
      Removes all elements from this Map, leaving it empty.

      This implementation calls entrySet().clear().

      Specified by:
      clear in interface Map<K,​V>
      Overrides:
      clear in class AbstractMap<K,​V>
      See Also:
      Map.isEmpty(), Map.size()
    • remove

      public V remove​(Object key)
      Description copied from class: AbstractMap
      Removes a mapping with the specified key from this Map.

      This implementation iterates its entry set, removing the entry with a key that key equals.

      Specified by:
      remove in interface Map<K,​V>
      Overrides:
      remove in class AbstractMap<K,​V>
      Parameters:
      key - the key of the mapping to remove.
      Returns:
      the value of the removed mapping or null if no mapping for the specified key was found.
    • firstEntry

      public Map.Entry<K,​V> firstEntry()
      Description copied from interface: NavigableMap
      Returns a key-value mapping associated with the least key in this map, or null if the map is empty.
      Specified by:
      firstEntry in interface NavigableMap<K,​V>
    • pollFirstEntry

      public Map.Entry<K,​V> pollFirstEntry()
      Description copied from interface: NavigableMap
      Removes and returns a key-value mapping associated with the least key in this map, or null if the map is empty.
      Specified by:
      pollFirstEntry in interface NavigableMap<K,​V>
      Returns:
      the removed first entry of this map, or null if this map is empty
    • firstKey

      public K firstKey()
      Description copied from interface: SortedMap
      Returns the least key in this sorted map.
      Specified by:
      firstKey in interface SortedMap<K,​V>
    • lastEntry

      public Map.Entry<K,​V> lastEntry()
      Description copied from interface: NavigableMap
      Returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
      Specified by:
      lastEntry in interface NavigableMap<K,​V>
    • pollLastEntry

      public Map.Entry<K,​V> pollLastEntry()
      Description copied from interface: NavigableMap
      Removes and returns a key-value mapping associated with the greatest key in this map, or null if the map is empty.
      Specified by:
      pollLastEntry in interface NavigableMap<K,​V>
      Returns:
      the removed last entry of this map, or null if this map is empty
    • lastKey

      public K lastKey()
      Description copied from interface: SortedMap
      Returns the greatest key in this sorted map.
      Specified by:
      lastKey in interface SortedMap<K,​V>
    • lowerEntry

      public Map.Entry<K,​V> lowerEntry​(K key)
      Description copied from interface: NavigableMap
      Returns a key-value mapping associated with the greatest key strictly less than the given key, or null if there is no such key.
      Specified by:
      lowerEntry in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      an entry with the greatest key less than key, or null if there is no such key
    • lowerKey

      public K lowerKey​(K key)
      Description copied from interface: NavigableMap
      Returns the greatest key strictly less than the given key, or null if there is no such key.
      Specified by:
      lowerKey in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      the greatest key less than key, or null if there is no such key
    • floorEntry

      public Map.Entry<K,​V> floorEntry​(K key)
      Description copied from interface: NavigableMap
      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.
      Specified by:
      floorEntry in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      an entry with the greatest key less than or equal to key, or null if there is no such key
    • floorKey

      public K floorKey​(K key)
      Description copied from interface: NavigableMap
      Returns the greatest key less than or equal to the given key, or null if there is no such key.
      Specified by:
      floorKey in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      the greatest key less than or equal to key, or null if there is no such key
    • ceilingEntry

      public Map.Entry<K,​V> ceilingEntry​(K key)
      Description copied from interface: NavigableMap
      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.
      Specified by:
      ceilingEntry in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      an entry with the least key greater than or equal to key, or null if there is no such key
    • ceilingKey

      public K ceilingKey​(K key)
      Description copied from interface: NavigableMap
      Returns the least key greater than or equal to the given key, or null if there is no such key.
      Specified by:
      ceilingKey in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      the least key greater than or equal to key, or null if there is no such key
    • higherEntry

      public Map.Entry<K,​V> higherEntry​(K key)
      Description copied from interface: NavigableMap
      Returns a key-value mapping associated with the least key strictly greater than the given key, or null if there is no such key.
      Specified by:
      higherEntry in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      an entry with the least key greater than key, or null if there is no such key
    • higherKey

      public K higherKey​(K key)
      Description copied from interface: NavigableMap
      Returns the least key strictly greater than the given key, or null if there is no such key.
      Specified by:
      higherKey in interface NavigableMap<K,​V>
      Parameters:
      key - the key
      Returns:
      the least key greater than key, or null if there is no such key
    • comparator

      public Comparator<? super K> comparator()
      Description copied from interface: SortedMap
      Returns the comparator used to compare keys in this sorted map, or null if the natural ordering is in use.
      Specified by:
      comparator in interface SortedMap<K,​V>
    • entrySet

      public Set<Map.Entry<K,​V>> entrySet()
      Description copied from interface: Map
      Returns a Set containing all of the mappings in this Map. Each mapping is an instance of Map.Entry. As the Set is backed by this Map, changes in one will be reflected in the other.
      Specified by:
      entrySet in interface Map<K,​V>
      Specified by:
      entrySet in class AbstractMap<K,​V>
      Returns:
      a set of the mappings
    • keySet

      public Set<K> keySet()
      Description copied from class: AbstractMap
      Returns a set of the keys contained in this Map. The Set is backed by this Map so changes to one are reflected by the other. The Set does 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.

      Specified by:
      keySet in interface Map<K,​V>
      Overrides:
      keySet in class AbstractMap<K,​V>
      Returns:
      a set of the keys.
    • subMap

      public NavigableMap<K,​V> subMap​(K from, boolean fromInclusive, K to, boolean toInclusive)
      Description copied from interface: NavigableMap
      Returns a view of the portion of this map whose keys range from fromKey to toKey. If fromKey and toKey are equal, the returned map is empty unless fromExclusive and toExclusive are 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 IllegalArgumentException on 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:
      subMap in interface NavigableMap<K,​V>
      Parameters:
      from - low endpoint of the keys in the returned map
      fromInclusive - true if the low endpoint is to be included in the returned view
      to - high endpoint of the keys in the returned map
      toInclusive - true if the high endpoint is to be included in the returned view
      Returns:
      a view of the portion of this map whose keys range from fromKey to toKey
    • subMap

      public SortedMap<K,​V> subMap​(K fromInclusive, K toExclusive)
      Description copied from interface: SortedMap
      Returns a sorted map over a range of this sorted map with all keys greater than or equal to the specified startKey and less than the specified endKey. 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.

      Specified by:
      subMap in interface NavigableMap<K,​V>
      Specified by:
      subMap in interface SortedMap<K,​V>
      Parameters:
      fromInclusive - the low boundary of the range (inclusive).
      toExclusive - the high boundary of the range (exclusive),
      Returns:
      a sorted map with the key from the specified range.
    • headMap

      public NavigableMap<K,​V> headMap​(K to, boolean inclusive)
      Description copied from interface: NavigableMap
      Returns a view of the portion of this map whose keys are less than (or equal to, if inclusive is 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 IllegalArgumentException on an attempt to insert a key outside its range.

      Specified by:
      headMap in interface NavigableMap<K,​V>
      Parameters:
      to - high endpoint of the keys in the returned map
      inclusive - true if 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 inclusive is true) toKey
    • headMap

      public SortedMap<K,​V> headMap​(K toExclusive)
      Description copied from interface: SortedMap
      Returns a sorted map over a range of this sorted map with all keys that are less than the specified endKey. 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.

      Specified by:
      headMap in interface NavigableMap<K,​V>
      Specified by:
      headMap in interface SortedMap<K,​V>
      Parameters:
      toExclusive - the high boundary of the range specified.
      Returns:
      a sorted map where the keys are less than endKey.
    • tailMap

      public NavigableMap<K,​V> tailMap​(K from, boolean inclusive)
      Description copied from interface: NavigableMap
      Returns a view of the portion of this map whose keys are greater than (or equal to, if inclusive is 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 IllegalArgumentException on an attempt to insert a key outside its range.

      Specified by:
      tailMap in interface NavigableMap<K,​V>
      Parameters:
      from - low endpoint of the keys in the returned map
      inclusive - true if 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 inclusive is true) fromKey
    • tailMap

      public SortedMap<K,​V> tailMap​(K fromInclusive)
      Description copied from interface: SortedMap
      Returns a sorted map over a range of this sorted map with all keys that are greater than or equal to the specified startKey. 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.

      Specified by:
      tailMap in interface NavigableMap<K,​V>
      Specified by:
      tailMap in interface SortedMap<K,​V>
      Parameters:
      fromInclusive - the low boundary of the range specified.
      Returns:
      a sorted map where the keys are greater or equal to startKey.
    • descendingMap

      public NavigableMap<K,​V> descendingMap()
      Description copied from interface: NavigableMap
      Returns 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 own remove operation), the results of the iteration are undefined.

      The returned map has an ordering equivalent to Collections.reverseOrder(comparator()). The expression m.descendingMap().descendingMap() returns a view of m essentially equivalent to m.

      Specified by:
      descendingMap in interface NavigableMap<K,​V>
      Returns:
      a reverse order view of this map
    • descendingKeySet

      public NavigableSet<K> descendingKeySet()
      Description copied from interface: NavigableMap
      Returns a reverse order NavigableSet view 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 own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
      Specified by:
      descendingKeySet in interface NavigableMap<K,​V>
      Returns:
      a reverse order navigable set view of the keys in this map