FindTheClosest

public class FindTheClosest {

    private final Number target;
    private final Number[] numbers;

    public FindTheClosest(Number target, Number[] numbers) {
        this.target = target;
        this.numbers = numbers;
    }

    public Number execute() {
        Stream<Number> stream = Arrays.stream(numbers);
        Optional<Number> optional = stream.min(Comparator.comparing(number -> {
            double delta = target.doubleValue() - number.doubleValue();
            return delta == 0 ? Integer.MAX_VALUE : Math.abs(delta + 1F / Integer.MAX_VALUE);
        }));
        return optional.orElse(target);
    }
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.