How to find closest number from a given value using lamba expression with java8 when i receive an Iterable from the parameter? [duplicate]

If you need a collection of n closest values, you will need to sort and slice the result:

public Iterable<Integer> findClosestNumbers(int givenValue, 
          Iterable<Integer> numbers, int n) {

    return StreamSupport.stream(numbers.spliterator(), false)
            .sorted(Comparator.comparingInt(i -> Math.abs(i - givenValue)))
            .limit(n)
            .collect(Collectors.toList());
}

This will return n (or fewer) numbers in ascending order of their distance from givenValue.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top