Sobes.tech
Middle

What is the complexity of searching for a method by key in a TreeMap collection?

sobes.tech AI

Answer from AI

The complexity of searching for a method by key in TreeMap is O(log n), where n is the number of elements in the collection.

This is because TreeMap is based on the data structure "red-black tree". In such a tree, balancing guarantees that the height of the tree logarithmically depends on the number of nodes. Search, insert, and delete operations require traversing the tree from the root to the desired node, which takes time proportional to the height of the tree.

// Example of searching in TreeMap
import java.util.TreeMap;

public class TreeMapSearch {

    public static void main(String[] args) {
        TreeMap<Integer, String> treeMap = new TreeMap<>();
        treeMap.put(5, "Five");
        treeMap.put(2, "Two");
        treeMap.put(8, "Eight");
        treeMap.put(1, "One");
        treeMap.put(6, "Six");

        // Search for element with key 8
        String value = treeMap.get(8);
        // The complexity of this operation is O(log n)
        System.out.println("Value for key 8: " + value);

        // Search for element with non-existent key 10
        String notFoundValue = treeMap.get(10);
        // The complexity of this operation is also O(log n)
        System.out.println("Value for key 10: " + notFoundValue);
    }
}