Home >Java >javaTutorial >Find position of element in Java TreeMap

Find position of element in Java TreeMap

王林
王林forward
2023-08-24 17:05:021142browse

在Java TreeMap中查找元素的位置

In Java, the TreeMap class provides an efficient way to store key-value pairs in an ordered manner. Sometimes, we may need to find out the position of a specific element in a TreeMap. In this article, we will explore different ways to accomplish this task. We'll discuss the syntax, algorithms, and provide executable code examples for each method.

grammar

To find the position of an element in Java TreeMap, we can use the following syntax -

int position = Collections.binarySearch(treeMap.values(), element);

Glossary explanation

Collections.binarySearch() strategy is used to perform binary search on sorted lists. In our case we pass the value of the TreeMap to the strategy and pass the component where we need to find the location. The policy returns the position of the component if the component is found in the list, otherwise it returns a negative value.

Method 1: Use binarySearch()

algorithm

  • Use the values() method to get values ​​from TreeMap.

  • Use Collections.binarySearch() to perform a binary search on values.

  • Store the result in a variable named position.

  • If the position is greater than or equal to 0, the element is found. Otherwise, it's not in the TreeMap.

Example

import java.util.Collections;
import java.util.TreeMap;

public class TreeMapPositionFinder {
   public static void main(String[] args) {
      TreeMap<Integer, String> treeMap = new TreeMap<>();
      treeMap.put(1, "Apple");
      treeMap.put(2, "Banana");
      treeMap.put(3, "Orange");
      treeMap.put(4, "Mango");

      String element = "Banana";

      int position = Collections.binarySearch(treeMap.values(), element);

      if (position >= 0) {
         System.out.println("Element found at position: " + (position + 1));
      } else {
         System.out.println("Element not found in the TreeMap.");
      }
   }
}

explain

In this method, we create a TreeMap and fill it with some key-value pairs. Then we define the element we are looking for, in this case "Banana". Use the Collections.binarySearch() method to search for elements within a TreeMap's values. If the element is found, we print its position by adding 1 to the position variable. Otherwise, we show that the element is not displayed in the TreeMap.

Method 2: Use TreeMap’s keySet() and get() methods

algorithm

  • Use keySet() method to get keySet from TreeMap.

  • Iterate over keys.

  • Check if the value associated with each key is equal to the element we are looking for.

  • If a match is found, the corresponding key is stored in a variable named position.

  • If position is not empty, it means that the element has been found. Otherwise, it does not exist in the TreeMap.

Example

import java.util.TreeMap;

public class TreeMapPositionFinder {
   public static void main(String[] args) {
      TreeMap<Integer, String> treeMap = new TreeMap<>();
      treeMap.put(1, "Apple");
      treeMap.put(2, "Banana");
      treeMap.put(3, "Orange");
      treeMap.put(4, "Mango");

      String element = "Banana";
      Integer position = null;

      for (Integer key : treeMap.keySet()) {
         if (treeMap.get(key).equals(element)) {
            position = key;
            break;
         }
      }

      if (position != null) {
         System.out.println("Element found at position: " + position);
      } else {
         System.out.println("Element not found in the TreeMap.");
      }
   }
}

Output

Element found at position: 2

explain

In this method, we again create a TreeMap and fill it with key-value pairs. We describe the component we need to find, in this case "Banana". We then use a for-each loop to iterate through the keys and check if the value associated with each key matches the element we are looking for. If a match is found, we store the corresponding key in the position variable. Finally, we check if the position is invalid to determine if the element is displayed in the TreeMap.

Method 3: Use the entrySet() and getValue() methods of TreeMap

algorithm

  • Use the entrySet() method to obtain the entrySet from the TreeMap.

  • Traverse the entries.

  • Check whether the value of each entry is equal to the element we are looking for.

  • If a match is found, the corresponding key is stored in a variable named position.

  • If position is not empty, it means that the element has been found. Otherwise, it does not exist in the TreeMap.

Example

import java.util.Map;
import java.util.TreeMap;

public class TreeMapPositionFinder {
   public static void main(String[] args) {
      TreeMap<Integer, String> treeMap = new TreeMap<>();
      treeMap.put(1, "Apple");
      treeMap.put(2, "Banana");
      treeMap.put(3, "Orange");
      treeMap.put(4, "Mango");

      String element = "Banana";
      Integer position = null;

      for (Map.Entry<Integer, String> entry : treeMap.entrySet()) {
         if (entry.getValue().equals(element)) {
            position = entry.getKey();
            break;
         }
      }

      if (position != null) {
         System.out.println("Element found at position: " + position);
      } else {
         System.out.println("Element not found in the TreeMap.");
      }
   }
}

Output

Element found at position: 2

explain

Similar to the second method, we create a TreeMap, populate it, and describe the components we need to discover. We then use a for-each loop to highlight the entries of the TreeMap and check if the value of each entry matches the component. If a match is found, we store the corresponding key in the position variable. Finally, we check if the position is invalid to determine if the component is displayed in the TreeMap.

Method 4: Use TreeMap’s values() method and indexOf()

algorithm

  • Use the values() method to get values ​​from TreeMap.

  • Use the indexOf() method to find the index of an element.

  • If the index is greater than or equal to 0, the element has been found. Otherwise, it's not in the TreeMap.

Example

import java.util.ArrayList;
import java.util.TreeMap;

public class TreeMapPositionFinder {
   public static void main(String[] args) {
      TreeMap<Integer, String> treeMap = new TreeMap<>();
      treeMap.put(1, "Apple");
      treeMap.put(2, "Banana");
      treeMap.put(3, "Orange");
      treeMap.put(4, "Mango");

      String element = "Mango";

      ArrayList<String> values = new ArrayList<>(treeMap.values());
      int position = values.indexOf(element);

      if (position >= 0) {
         System.out.println("Element found at position: " + (position + 1));
      } else {
         System.out.println("Element not found in the TreeMap.");
      }
   }
}

Output

Element found at position: 4

explain

In this method, we first create a TreeMap and populate it. We describe the component we need to discover, here "Banana". Then, we use the values() method to create an ArrayList containing the TreeMap values. We find the index of the component in the ArrayList using the indexOf() method. If the index is greater than or equal to 0, we print out the component's position. Otherwise, we indicate that the element is not displayed in the TreeMap.

in conclusion

In this article, we explored different ways to find the position of an element in a Java TreeMap. We examine language constructs, computations, and provide executable code examples for each approach. Depending on your specific needs and preferences, you can choose the method that best suits your needs. The TreeMap course in Java provides a powerful and efficient way to store and manipulate sorted data, enabling you to perform various operations with ease.

The above is the detailed content of Find position of element in Java TreeMap. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete