# 在ordererd列表中查找最接近的值

public class Closest {

private static List integers = new ArrayList();

static {
for (int i = 0; i <= 10; i++) {
}
}

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);
}
}


## 最佳答案

public int closest(int of, List 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;
}


private final static List 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));
}