Languages
[Edit]
EN

Java - Math.min() with multiple arguments

7 points
Created by:
Kourtney-White
335

In this short article, we would like to show a simple Java alternative Math.min() function implementation that lets to pass multiple arguments and returns a minimum value (pass more than 2 arguments).

Practical example:

import java.util.Comparator;

public class Program {

    private static <T> T findMin(Comparator<T> comparator, T... values) {
        if (values.length == 0) {
            return null;
        }
        T result = values[0];
        for (int i = 1; i < values.length; ++i) {
            T value = values[i];
            int order = comparator.compare(value, result);
            if (order < 0) {
                result = value;
            }
        }
        return result;
    }


    // Usage example:

    public static void main(String[] args) {

        System.out.println(findMin(Integer::compare, 5,  4,  3,  2     ));             // 2
        System.out.println(findMin(Long::compare,    5L, 4L, 3L, 2L, 1L));             // 1

        System.out.println(findMin(Float::compare,  3.0f, 2.0f, 1.0f, 0.0f     ));     //  0.0
        System.out.println(findMin(Double::compare, 3.0,  2.0,  1.0,  0.0, -1.0));     // -1.0

        System.out.println(findMin(Byte::compare,   (byte) 5,  (byte) 4           ));  // 4
        System.out.println(findMin(Short::compare, (short) 5, (short) 4, (short) 3));  // 3
    }
}

Output:

4
3
2
1
0.0
-1.0
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join