Find closest value in an ordererd list
<p>I am wondering how you would write a simple java method finding the closet Integer to a given value in a sorted Integer list.</p>

<p>Here is my first attempt:</p>

<pre><code>public class Closest {

    private static List&lt;Integer&gt; integers = new ArrayList&lt;Integer&gt;();

    static {
     for (int i = 0; i &lt;= 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 &lt; 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 &lt; 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);
    }
}
</code></pre>

<p>What do you think about this solution ? I am sure there is a cleaner way to do this job ...</p>

<p>Maybe such method exists somewhere in the Java libraries and I missed it ??</p>

<p>Manu </p>
