user7085962 user7085962 - 1 month ago 5
Java Question

Find position of item after sort?

So I am trying to take advantage of RecyclerView animations by using notifyItemRemoved / Added on the adapter, as opposed to just notifyDataSetChanged, which appears to refresh the list instantly without anything cool happening.

But when adding a new item to the list, I normally sort it first using Collections.sort(list) so it appears in the correct spot. Is there an easy way to tell which position the newly-added item went to during this sort, or am I stuck doing a boring linear scan / home-rolled binary search?

Answer

If you want all elements inserted in sort order, don't do add, sort, add, sort, add, sort, ...

That's about the slowest way of doing it.

To do an insert in the correct position (index), find that position using Collections.binarySearch(), then call the add(int index, E element) to do the actual insert.