Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaJava TreeMap Special Methods

Java TreeMap Special Methods

TreeMap in Java is used to implement Map interface and NavigableMap along with the AbstractMap Class. 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. Due to the implementation of the NavigableMap interface and sorted data, TreeMap provides certain special functions which are not present in any other map implementation.

Method 1: firstKey()

It returns the first (lowest) key currently in the map.

Syntax: 

public K firstKey()

Return Value: The first (lowest) key currently in this map.

Note: NoSuchElementException is thrown if this map is empty.

Example:

Java




//  Java Program to illustrate firstKey() method of TreeMap
 
// Importing input output classes
import java.io.*;
// Importing treeMap class from java.util package
import java.util.TreeMap;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap of type Character
        // and String
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Inserting elements to the object created above
 
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Display all the elements in the object of TreeMap
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display the lowest key
        // using firstkey() method
        System.out.println("Lowest Key is : "
                           + treeMap.firstKey());
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Lowest Key is : A

Method 2: lastKey()

The java.util.TreeMap.lastKey() is used to retrieve the last or the highest key present in the map.

Syntax:  

tree_map.lastKey();

Return Value: The method returns the last key present in the map.

Exception: The method throws NoSuchElementException if the map is empty.

Example:

Java




// Java Program to illustrate lastKey() Method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing TreeMap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap of type Character
        // and Integer
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to the object created above
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Print and display all the elements in the TreeMap
        System.out.println("Tree Map : " + treeMap);
 
        // Print the highest key in the TreeMap
        // using lastKey() method
        System.out.println("Highest Key is : "
                           + treeMap.lastKey());
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Highest Key is : M

Method 3: headMap(Object key_value)

The java.util.TreeMap.headMap(key_point) method of TreeMap class is used to get all the pairs or portion of the map strictly less than the parameter key_value. The mentioned parameter is excluded from the newly prepared TreeMap. Since the set is backed by the map, so any changes to the map are reflected in the other map, and vice-versa.

Syntax:

sorted_map = old_treemap.headMap(key_point)

Parameters: The method takes one parameter key_point of the type of key taken in the TreeMap and refers to the point, till which the key-value pair is to be returned.

Return Value: The method returns the portion of the treemap whose keys are strictly less than that of the key_point.

Exceptions: The method throws three type of exceptions: 

  • ClassCastException: This exception is thrown when the key_point is not compatible or comparable to the maps comparator.
  • NullPointerException: This exception is thrown when the key-point is Null.
  • IllegalArgumentException: This exception is thrown when the key_point is out of bound or outside the limit of the map range.

Example:

Java




// Java Program to illustrate headMap() method of TreeMap
 
// Importing input output classes
import java.io.*;
// Importing TreeMap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap of character and
        // Integer type
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to the object of TreeMap
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Print and display all elements in the object
        System.out.println("Tree Map : " + treeMap);
 
        // Print elements inclusive of key value passed
        // using headMap() method
        System.out.println(
            "Head Map exclusive of the key value : "
            + treeMap.headMap('G'));
 
        // Similarly to include the value passed
        // We can add a boolean argument as
        System.out.println(
            "Head Map inclusive of the key value : "
            + treeMap.headMap('G', true));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Head Map exclusive of the key value : {A=1, F=5}
Head Map inclusive of the key value : {A=1, F=5, G=4}

Method 4: subMap(K startKey, K endKey)

The java.util.TreeMap.subMap(K startKey, K endKey) method in Java is used to return the part or portion of the map defined by the specified range of keys in the parameter. Any changes made in one or the other map will reflect the change in the other map.

Syntax:

Tree_Map.subMap(K startKey, K endKey)

 Parameters: The method takes two parameters of Key type:

  • startKey: This refers to the starting point or lower end of the map including which the points are to be considered.
  • endKey: This refers to the endpoint or the higher end of the map excluding which the points are to be considered.

Note: If startKey is equal to the endKey then a Null Map is returned.

Return Value: The method returns another map containing the part or portion of the map within the specified range.

Exceptions: The method throws three types of exceptions:

  • ClassCastException: This exception is thrown if the parameters mentioned in the method cannot be compared with the keys of this map.
  • NullPointerException: This exception is thrown if either of the parameters is of null type and the map does not accept any null values.
  • IllegalArgumentException: This exception is thrown if the mentioned parameters are out of range or the lower end is greater than the higher end.

 

 Example:

Java




// Java Program to illustrate subMap() Method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing TreeMap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap
        // Declaring object of Character and Integer type
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to the TreeMap object
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Print and display all elements of the TreeMap
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display commands illustrating subMap()
        // method
        System.out.println(
            "Submap between the F(inclusive) and K(exclusive) : "
            + treeMap.subMap('F', 'K'));
        System.out.println(
            "Submap between the F(inclusive) and K(inclusive) : "
            + treeMap.subMap('F', true, 'K', true));
        System.out.println(
            "Submap between the F(exclusive) and K(inclusive) : "
            + treeMap.subMap('F', false, 'K', true));
        System.out.println(
            "Submap between the F(exclusive) and K(inclusive) : "
            + treeMap.subMap('F', false, 'K', true));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Submap between the F(inclusive) and K(exclusive) : {F=5, G=4, J=7}
Submap between the F(inclusive) and K(inclusive) : {F=5, G=4, J=7, K=9}
Submap between the F(exclusive) and K(inclusive) : {G=4, J=7, K=9}
Submap between the F(exclusive) and K(inclusive) : {G=4, J=7, K=9}

Method 5: higherKey()

The higherKey() method is used to return the least key strictly greater than the given key, or null if there is no such key.

Example:

Java




// Java Program to illustrate higherKey() method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing TreeMap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap object
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to TreeMap objects
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Print and display all TreeMap elements
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display the higher key
        // using higherKey() method
        System.out.println("Higher key for F : "
                           + treeMap.higherKey('F'));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Higher key for F : G

Method 6: ceilingKey(key) Method 

The ceilingKey() function returns the least key greater than or equal to the given key or null if such a key is absent.

Example:

Java




// Java Program to illustrate ceilingKey() Method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing treeMap class from java.util package
import java.util.TreeMap;
 
// main class
class GFG {
 
    // main driver method
    public static void main(String[] args)
    {
        // Creating an object of TreeMap object
        // Declaring object of Character and Integer type
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to the object created above
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // print and display all elements of the treeMap
        // object
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display ceiling key among all entries
        // using ceilingKey() method
 
        // Case 1
        System.out.println("Ceiling key for D : "
                           + treeMap.ceilingKey('D'));
 
        // Case 2
        System.out.println("Ceiling key for F : "
                           + treeMap.ceilingKey('F'));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Ceiling key for D : F
Ceiling key for F : F

Method 7: lowerKey(key) Method 

The lowerKey() method is used to return the greatest key strictly less than to given key, passed as the parameter.

Example:

Java




// Java Program to illustrate lowerkey() method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing TreeMap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap
        // Declaring object of type - Character and Integer
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to above object
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // print and display the TreeMap elements
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display the lower key
        // using lowerKey() method
        System.out.println("Lower key for N : "
                           + treeMap.lowerKey('N'));
        System.out.println("Lower key for M : "
                           + treeMap.lowerKey('M'));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Lower key for N : M
Lower key for M : K

Method 8: floorKey(key) 

The floorKey() method is used to return the greatest key less than or equal to the given key from the parameter.

Example:

Java




// Java Program to illustrate floorKey() method in TreeMap
 
// Importing input output classes
import java.io.*;
// Importing Treemap class from java.util package
import java.util.TreeMap;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an object of TreeMap of character and
        // Integer type
        TreeMap<Character, Integer> treeMap
            = new TreeMap<>();
 
        // Adding elements to TreeMap
        // Custom entries
        treeMap.put('A', 1);
        treeMap.put('F', 5);
        treeMap.put('M', 2);
        treeMap.put('K', 9);
        treeMap.put('G', 4);
        treeMap.put('J', 7);
 
        // Print and display the treeMap
        System.out.println("Tree Map : " + treeMap);
 
        // Print and display the floor key
        // using the floorKey() method
        System.out.println("Floor key for N : "
                           + treeMap.floorKey('N'));
       
        System.out.println("Floor key for M : "
                           + treeMap.floorKey('M'));
    }
}


Output

Tree Map : {A=1, F=5, G=4, J=7, K=9, M=2}
Floor key for N : M
Floor key for M : M
RELATED ARTICLES

Most Popular

Recent Comments