Find the closest value among a List of Integer - Android java.util

Android examples for java.util:List

Description

Find the closest value among a List of Integer

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static int closest(int of, List<Integer> in) {
        int min = Integer.MAX_VALUE;
        int closest = of;
        int index = 0;

        for (int v : in) {
            final int diff = Math.abs(v - of);

            if (diff < min) {
                min = diff;/*www.  ja  v  a2  s.c  o  m*/
                closest = v;
            }
            index++;
        }

        return closest;
    }
}

Related Tutorials