I have an array
int [ ][ ] matrix = {{ 10, 23, 93, 44 },{ 22, 34, 25, 3 },{ 84, 11, 7, 52 }};
and I want to find the max value on the first column of this array which is 84
This is my whole code which give me the max value of each column in this array
public class Sample {
public static void main(String[] args) {
int[][] matrix = {{10, 23, 93, 44}, {22, 34, 25, 3}, {84, 11, 7, 52}};
int[] max = matrix[0];
for (int row = 1; row < matrix.length; row ) {
for (int column = 0; column < matrix[0].length; column ) {
if (matrix[row][column] > max[column]) {
max[column] = matrix[row][column];
}
}
}
for (int number : max) {
System.out.print(number " ");
}
}}
CodePudding user response:
public static void main(String[] args) {
int[][] matrix = {{10, 23, 93, 44}, {22, 34, 25, 3}, {84, 11, 7, 52}};
int max = matrix[0][0];
for (int row = 1; row < matrix.length; row ) {
if (max < matrix[row][0]) {
max = matrix[row][0];
}
}
System.out.println(max);
}
CodePudding user response:
If the maximum value of only one column needs to be found, then no nested loop is needed:
static int maxOfFirstColumn(int[][] arr) {
int max = Integer.MIN_VALUE;
for (int[] row : arr) {
if (null != row && row.length > 0) {
max = Math.max(max, row[0]);
}
}
return max;
}
Solution using Stream API:
static int maxOfFirstColumn(int[][] arr) {
return Arrays.stream(arr) // Stream<int[]>
.filter(Objects::nonNull)
.filter(row -> row.length > 0)
.mapToInt(row -> row[0]) // IntStream
.max()
.getAsInt();
}
