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

jtbandes picture jtbandes · Oct 27, 2011 · Viewed 43.1k times · Source

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

Answer

jtbandes picture jtbandes · Oct 27, 2011

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.