I'm using a TreeSet<Integer>
and I'd quite simply like to find the index of a number in the set. Is there a nice way to do this that actually makes use of the O(log(n)) complexity of binary trees?
(If not, what should I do, and does anyone know why not? I'm curious why such a class would be included in Java without something like a search function.)
The TreeSet class in Java doesn't have the ability to find the index of a number in the set.
TreeSet first() Method in Javafirst() method is used to return the first of the element of a TreeSet. The first element here is being referred to the lowest of the elements in the set. If the elements are of integer types then the smallest integer is returned.
The comparator() method been present inside java. util. TreeSet shares an important function of setting and returning the comparator that can be used to order the elements in a TreeSet. The method returns a Null value if the set follows the natural ordering pattern of the elements.
I poked around TreeSet and its interfaces for a while, and the best way I found to get the index of an element is:
set.headSet(element).size()
headSet(element)
returns the sub-TreeSet
of elements less than its argument, so the size of this set will be the index of the element in question. A strange solution indeed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With