Java TreeMap class

Java TreeMap class implements the Map interface by using a tree. It provides an efficient means of storing key/value pairs in sorted order.

The important points about Java TreeMap class are:

  • A TreeMap contains values based on the key. It implements the NavigableMap interface and extends AbstractMap class.
  • It contains only unique elements.
  • It cannot have null key but can have multiple null values.
  • TreeMap class declaration

    public class TreeMap extends AbstractMap implements NavigableMap, Cloneable, Serializable

    Constructors

    TreeMap() It is used to construct an empty tree map that will be sorted using the natural order of its key.

    TreeMap(Comparator comp) It is used to construct an empty tree-based map that will be sorted using the comparator comp.

    TreeMap(Map m) It is used to initialize a tree map with the entries from m, which will be sorted using the natural order of the keys.

    TreeMap(SortedMap sm) sm) It is used to initialize a tree map with the entries from the SortedMap sm, which will be sorted in the same order as sm.

    Method

    boolean containsKey(Object key) It is used to return true if this map contains a mapping for the specified key.

    boolean containsValue(Object value) It is used to return true if this map maps one or more keys to the specified value.

    Object firstKey() It is used to return the first (lowest) key currently in this sorted map.

    Object get(Object key) It is used to return the value to which this map maps the specified key.

    Object lastKey() It is used to return the last (highest) key currently in this sorted map

    Object remove(Object key) It is used to remove the mapping for this key from this TreeMap if present.

    EXAMPLE

    Flash Soon



    Copyright ©2017 Design& development by HN