I have a list of more than 37K items, and I already implemented hashCode()
, equals()
, so I wonder Collections.binarySearch()
can help improve the performance and faster than indexOf()
method.
Collections. binarySearch() method is a java. util. Collections class method that returns position of an object in a sorted list.
If you need fast access to elements using index, ArrayList should be choice. If you need fast access to elements using a key, use HashMap. If you need fast add and removal of elements, use LinkedList (but it has a very poor seeking performance).
In order to perform Binary Search on ArrayList with Java Collections, we use the Collections. binarySearch() method. If key is not present, the it returns ((insertion point) + 1) *(-1).
The indexOf method on List uses a linear search with O(n) time complexity. Binary search has O(log n) time complexity, which scales much better for large data sets if you are doing repeated lookups.
If your collection is sorted, binarySearch()
will be O(log n) as opposed to indexOf()
's O(n) and you will definitely see an improvement.
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