I need a way to calculate the number of elements less than X in a TreeSet
of Integers really fast.
I can use the
- subSet()
- headSet()
- tailSet()
methods but they are really slow (I just need the count, not the numbers themselves). Is there a way?
Thank you.
EDIT:
I found a workaround that makes things a lot faster! I am using BitSet and it's cardinality() method. I create a BitSet at first and for every element added to the TreeSet I set the corresponding index in BitSet. Now, to count the number of elements less than X I use:
bitset.get(0, X+1).cardinality()
This is much faster compared with treeset.subSet(0, true, X, true).size().
Anyone knows why? I assume BitSet.cardinality() doesn't use linear search.