Junior — Middle
Does TreeMap sort elements by key when adding them?
sobes.tech AI
Answer from AI
Yes, TreeMap in Java stores elements in sorted order by key. When adding a new element, TreeMap uses either the natural ordering of the keys (if the keys implement Comparable) or a provided comparator (Comparator) to determine the position for insertion.
Thus, the elements are always ordered, and search, insert, and delete operations are performed with logarithmic complexity.
Example:
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "three");
map.put(1, "one");
map.put(2, "two");
System.out.println(map.keySet()); // [1, 2, 3]