Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the index of an element in a TreeSet?

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.)

like image 934
jtbandes Avatar asked Oct 27 '11 04:10

jtbandes


People also ask

Does tree set have index?

The TreeSet class in Java doesn't have the ability to find the index of a number in the set.

How do you get the first element in TreeSet?

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.

Does TreeSet have comparator method?

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.


1 Answers

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.

like image 91
jtbandes Avatar answered Sep 17 '22 19:09

jtbandes