Find the Position of an Element in a Java TreeMap


In Java, the TreeMap class gives a productive way to store key-value sets in a sorted way. Now and then, we may have to discover the position of a specific element inside a TreeMap. In this article, we are going to investigate distinctive approaches to achieve this task. We'll talk about the sentence structure, calculations, and give ready-to-execute code illustrations for each approach.

Syntax

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

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

Explanation of Syntax

The Collections.binarySearch() strategy is utilized to perform a double look on a sorted list. In our case, we are passing the values of the TreeMap to the strategy and the component we need to discover the position of. The strategy returns the list of the component in the event that it is found within the list, or a negative value otherwise.

Approach 1: Using binarySearch()

Algorithm

  • Get the values from the TreeMap using the values() method.

  • Perform a binary search on the values using Collections.binarySearch().

  • Store the result in a variable called position.

  • If position is greater than or equal to 0, the element is found. Otherwise, it is not present 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.");
      }
   }
}

Explanation

In this approach, we make a TreeMap and populate it with a few key-value pairs. We at that point characterize the component we need to discover, which is "Banana" in this case. The Collections.binarySearch() strategy is utilized to search for the component inside the values of the TreeMap. In the event that the component is found, we print its position by including 1 to the position variable. Otherwise, we show that the component is not displayed within the TreeMap.

Approach 2: Using TreeMap's keySet() and get() methods

Algorithm

  • Get the keySet from the TreeMap using the keySet() method.

  • Iterate over the keys.

  • Check if the value associated with each key is equal to the element we want to find.

  • If a match is found, store the corresponding key in a variable called position.

  • If position is not null, the element is found. Otherwise, it is not present 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

Explanation

In this approach, we once more make a TreeMap and populate it with key-value sets. We characterize the component we need to discover, which is "Banana" in this case. We at that point repeat over the keys employing a for-each circle and check in the event that the esteem related with each key matches the element we are trying to find. If a coordinate is found, we store the corresponding key within the position variable. Finally, we check on the off chance that the position isn't invalid to decide in the event that the component is displayed within the TreeMap.

Approach 3: Using TreeMap's entrySet() and getValue() methods

Algorithm

  • Get the entrySet from the TreeMap using the entrySet() method.

  • Iterate over the entries.

  • Check if the value of each entry is equal to the element we want to find.

  • If a match is found, store the corresponding key in a variable called position.

  • If position is not null, the element is found. Otherwise, it is not present 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

Explanation

Comparable to approach 2, we make a TreeMap, populate it, and characterize the component we need to discover. We at that point emphasize over the passages of the TreeMap employing a for-each circle and check in case the esteem of each section matches the component. In the event that a coordinate is found, we store the comparing key within the position variable. At long last, we check in the event that the position is not invalid to decide on the off chance that the component is displayed within the TreeMap.

Approach 4: Using TreeMap's values() method and indexOf()

Algorithm

  • Get the values from the TreeMap using the values() method.

  • Find the index of the element using the indexOf() method.

  • If the index is greater than or equal to 0, the element is found. Otherwise, it is not present 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

Explanation

In this approach, we first make a TreeMap and populate it. We characterize the component we need to discover, which is "Banana" in this case. We at that point make an ArrayList containing the values of the TreeMap utilizing the values() strategy. We utilize the indexOf() strategy to discover the file of the component within the ArrayList. In the event that the file is more noteworthy than or breaks even with 0, we print the position of the component. Otherwise, we indicate that the element isn't shown within the TreeMap.

Conclusion

In this article, we explored different approaches to find the position of an element in a Java TreeMap. We examined the language structure, calculations, and gave ready-to-execute code illustrations for each approach. Depending on your specific necessities and inclinations, you will be able select the approach that best suits your needs. The TreeMap lesson in Java gives a capable and productive way to store and control sorted information, permitting you to perform different operations with ease.

Updated on: 31-Jul-2023

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements