Find the nearest/closest value in a sorted List

前端 未结 8 1659
我寻月下人不归
我寻月下人不归 2020-12-05 10:59

I was wondering if it is possible to find the closest element in a List for a element that is not there.

For example if we had the valu

8条回答
  •  感动是毒
    2020-12-05 11:23

    Andrey's answer is correct. Just expanding on it a bit.
    No need to reinvent the wheel when you can use the built in binary search.

    You can find the indices with:

    int leftIndex = (-Collections.binarySearch(allItems, key) - 2);
    int rightIndex = (-Collections.binarySearch(allItems, key) - 1);
    

    The item in the list will need to implement Comparable. Simple types like String and Integer already implement this. Here's an example https://www.javatpoint.com/Comparable-interface-in-collection-framework.

    Depending on your use case you may want to do index = Math.max(0, index) after the binary search just to be safe.

提交回复
热议问题