Java TreeMap

Facebooktwitterredditpinterestlinkedinmailby feather

TreeMap in Java with Example

Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted order. The values based on the key. It contains unique elements, i.e. it does not contain the duplicate values. It does not provide null keys but contains multiple null values. It maintains the ascending order. If you assign a null key, then it throws NullPointerException. It is not synchronized, so it is not thread-safe.

Time Complexity of TreeMap:

TreeMap based on Red-Black Tree data structure. The complexity of the TreeMap is O(log n) time.

The constructor of TreeMap:

  1. TreeMap (): It is used to construct the empty TreeMap which is natural sorted.
  2. TreeMap (Map m): It is used to initialize the treemap with the entries of map m which is natural sorted.
  3. TreeMap (Comparator c): It is used to construct the empty tree-based map which sorted by using Comparator.
  4. TreeMap (SortedMap s): It is used to initializes the treemap with entries from s, which sorted as SortedMaps.

Methods of TreeMap:

  1. containsKey (Object key): it returns true if the specified key is present in the TreeMap.

Example:

Output:

  1. containsValue (Object value): It returns true if the specified value is present in the TreeMap.

Example:

Output:

  1. get (Object Key): It is used to get the value of a particular key from the map.

Example:

Output:

  1. put (object K, object V): It is used to insert the value of the specified key in the Map.

Example:

Output:

  1. clear (): It is used to remove all mapping from the TreeMap.

Example:

Output:

  1. clone (): This is used to return the same copy of the TreeMap.

Example:

Output:

  1. size (): This method is used to return the size of the TreeMap.

Example:

Output:

  1. putAll (Map m): This is used to copy all elements from the map to another map.

Example:

Output:

  1. keySet (): It returns the set view of keys in the TreeMap.

Example:

Output:

  1. Values (): This returns the collections view of values in the TreeMap.

Example:

Output:

  1. entrySet (): This returns the Set view of the whole mapping in the map.

Example:

Output:

  1. firstKey (): This returns the first (lowest) key in the sorted TreeMap.

Example:

Output:

  1. lastKey (): This returns the last (highest) key in the sorted TreeMap.

Example:

Output:

  1. remove (Object K): It is used to remove the mapping of the specified key from the TreeMap.

Example:

Output:

  1. headMap (Object key): This method is used to view the only portion of the map which is less than the parameter key.

Example:

Output:

  1. subMap (Object start key, Object endKey): This method is used to view the portion of the map between the ranges of starting point of the key to the end point of key.

Example:

Output:

Facebooktwitterredditpinterestlinkedinmailby feather