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
It seems like the easiest way is simply to iterate over the sorted list, checking each item.
List ints = new ArrayList<>();
ints.add(1);
ints.add(3);
ints.add(6);
ints.add(7);
Collections.sort(ints);
int target = 4;
int nearest = 0;
for (int i : ints)
{
if (i <= target) {
nearest = i;
}
}
System.out.println(nearest);
This outputs the largest item in the list which is less than or equal to the target
.