Open In App

Find the position of an element in a Java TreeMap

Last Updated : 27 Dec, 2019
Improve
Improve
Like Article
Like
Save
Share
Report

Given an element N and a TreeMap, the task is to find the position of this element in the given TreeMap in Java.

Examples:

Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 20
Output: 2

Input: TreeMap = {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}, N = 5
Output: -1

Approach:

  • There is no direct method to find out the position of the key in a TreeMap.
  • However, we can use TreeMap headMap() method.
  • The method returns the portion of the treemap whose keys are strictly less than that of the key_point.
  • Hence, if the key exists in the TreeMap, then the size() of its headMap is equal to the position of the key in the TreeMap.

Below is the implementation of the above approach:




// Java code to find the position
// of an element in a Java TreeMap
  
import java.util.*;
  
public class Tree_Map_Demo {
  
    // Function to return the position of
    // the specified element in the given TreeMap
    public static <K, V> int findPosition(K N, TreeMap<K, V> tree_map)
    {
        int pos = -1;
  
        // Check if the given key
        // is present or not
        if (tree_map.containsKey(N)) {
  
            // If present, find the position
            // using the size of headMap()
  
            pos = tree_map.headMap(N).size();
        }
  
        return pos;
    }
  
    // Function to print the result
    public static <K, V> void printResult(K N, TreeMap<K, V> tree_map)
    {
  
        // Get the position
        int pos = findPosition(N, tree_map);
  
        // Print the result
        if (pos >= 0) {
  
            System.out.println(N + " found at "
                               + "position = " + pos);
        }
        else {
  
            System.out.println(N + " not found. "
                               + "Hence position = "
                               + pos);
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating an empty TreeMap
        TreeMap<Integer, String> tree_map
            = new TreeMap<Integer, String>();
  
        // Mapping string values to int keys
        tree_map.put(10, "Geeks");
        tree_map.put(15, "4");
        tree_map.put(20, "Geeks");
        tree_map.put(25, "Welcomes");
        tree_map.put(30, "You");
  
        // Displaying the TreeMap
        System.out.println("TreeMap: " + tree_map);
  
        // Element of which position is to be found
        int N1 = 20, N2 = 5;
  
        // Get the position
        printResult(N1, tree_map);
        printResult(N2, tree_map);
    }
}


Output:

TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
20 found at position = 2
5 not found. Hence position = -1


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads