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
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.