Can you use Math.max with an array?
15,398
Solution 1
Can you use Math.max with an array?
No, but...
If you're using Java 8, you can use streams:
Arrays.stream(array).max().getAsInt()
Otherwise you can write a simple utility method to do it for you:
public static int max(int... array) {
if (array.length == 0) {
// ...
}
int max = array[0];
for (int a : array) {
if (a > max)
max = a;
}
return max;
}
Solution 2
// Initializing array of integers
Integer[] num = { 2, 4, 7, 5, 9 };
// using Collections.max() to find minimum element
// using only 1 line.
int max = Collections.max(Arrays.asList(num));
Author by
cherry
Updated on June 14, 2022Comments
-
cherry almost 2 years
package prova1; import javax.swing.JOptionPane; /** * * @author OOO */ public class Prova1 { public static void main(String[] args) { int array[] = new int[10]; for (int i = 0; i < array.length; i++) { String input = JOptionPane.showInputDialog("Insert number"); array[i] = Integer.parseInt(input); } JOptionPane.showMessageDialog(null, Math.max(array)); } }
-
Willem Van Onsem almost 10 yearsProposal: change
int[]
toint...