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.) As @Yrlec points out set.headSet(element).size will returns 0 though there is no this element in the set. So we'd better check: return set.contains(element)? set.headSet(element).size(): -1; Here is a test case to show the problem: public static