EN
Java - Math.min() with multiple arguments
7 points
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:
xxxxxxxxxx
1
import java.util.Comparator;
2
3
public class Program {
4
5
private static <T> T findMin(Comparator<T> comparator, T... values) {
6
if (values.length == 0) {
7
return null;
8
}
9
T result = values[0];
10
for (int i = 1; i < values.length; ++i) {
11
T value = values[i];
12
int order = comparator.compare(value, result);
13
if (order < 0) {
14
result = value;
15
}
16
}
17
return result;
18
}
19
20
21
// Usage example:
22
23
public static void main(String[] args) {
24
25
System.out.println(findMin(Integer::compare, 5, 4, 3, 2 )); // 2
26
System.out.println(findMin(Long::compare, 5L, 4L, 3L, 2L, 1L)); // 1
27
28
System.out.println(findMin(Float::compare, 3.0f, 2.0f, 1.0f, 0.0f )); // 0.0
29
System.out.println(findMin(Double::compare, 3.0, 2.0, 1.0, 0.0, -1.0)); // -1.0
30
31
System.out.println(findMin(Byte::compare, (byte) 5, (byte) 4 )); // 4
32
System.out.println(findMin(Short::compare, (short) 5, (short) 4, (short) 3)); // 3
33
}
34
}
Output:
xxxxxxxxxx
1
4
2
3
3
2
4
1
5
0.0
6
-1.0