Find closest value in an ordered list
java
Solution
try this little method:
public int closest(int of, List<Integer> in) {
int min = Integer.MAX_VALUE;
int closest = of;
for (int v : in) {
final int diff = Math.abs(v - of);
if (diff < min) {
min = diff;
closest = v;
}
}
return closest;
}
some testcases:
private final static List<Integer> list = Arrays.asList(10, 20, 30, 40, 50);
@Test
public void closestOf21() {
assertThat(closest(21, list), is(20));
}
@Test
public void closestOf19() {
assertThat(closest(19, list), is(20));
}
@Test
public void closestOf20() {
assertThat(closest(20, list), is(20));
}
Problem
I am wondering how you would write a simple java method finding the closest Integer to a given value in a sorted Integer list. Here is my first attempt: ``` public class Closest { private static List<Integer> integers = new ArrayList<Integer>(); static { for (int i = 0; i <= 10; i++) { integers.add(Integer.valueOf(i * 10)); } } public static void main(String[] args) { Integer closest = null; Integer arg = Integer.valueOf(args[0]); int index = Collections.binarySearch( integers, arg); if (index < 0) /*arg doesn't exist in integers*/ { index = -index - 1; if (index == integers.size()) { closest = integers.get(index - 1); } else if (index == 0) { closest = integers.get(0); } else { int previousDate = integers.get(index - 1); int nextDate = integers.get(index); if (arg - previousDate < nextDate - arg) { closest = previousDate; } else { closest = nextDate; } } } else /*arg exists in integers*/ { closest = integers.get(index); } System.out.println("The closest Integer to " + arg + " in " + integers + " is " + closest); } } ``` What do you think about this solution ? I am sure there is a cleaner way to do this job. Maybe such method exists somewhere in the Java libraries and I missed it ?