📜  在Java TreeMap 中查找元素的位置

📅  最后修改于: 2022-05-13 01:54:40.527000             🧑  作者: Mango

在Java TreeMap 中查找元素的位置

给定一个元素 N 和一个 TreeMap,任务是在Java中找到这个元素在给定 TreeMap 中的位置。

例子:

方法:

  • 没有直接的方法可以找出键在 TreeMap 中的位置。
  • 但是,我们可以使用 TreeMap headMap() 方法。
  • 该方法返回树形图中其键严格小于 key_point 的部分。
  • 因此,如果key存在于TreeMap中,那么它的headMap的size()就等于key在TreeMap中的位置。

下面是上述方法的实现:

// 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  int findPosition(K N, TreeMap 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  void printResult(K N, TreeMap 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 tree_map
            = new TreeMap();
  
        // 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);
    }
}
输出:
TreeMap: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
20 found at position = 2
5 not found. Hence position = -1