A more convenient way to find a maximum of 2+ numbers?

I need a code that takes more than 2 integers and outputs the largest. I used Math.MAX , but the problem is that it only accepts 2 integers by default, and you cannot print all ints in it. Therefore, I had to do it as follows:

 int max = Math.max(a, Math.max(b, Math.max(c, Math.max(d, e)))); 

Is there a better way to do this?

+4
source share
2 answers

You can use varargs :

 public static Integer max(Integer... vals) { Integer ret = null; for (Integer val : vals) { if (ret == null || (val != null && val > ret)) { ret = val; } } return ret; } public static void main(String args[]) { System.out.println(max(1, 2, 3, 4, 0, -1)); } 

As an alternative:

 public static int max(int first, int... rest) { int ret = first; for (int val : rest) { ret = Math.max(ret, val); } return ret; } 
+6
source

You can use a simple loop:

 public Integer max(final Collection<Integer> ints) { Integer max = Integer.MIN_VALUE; for (Integer integer : ints) { max = Math.max(max, integer); } return max; } 
+1
source

All Articles