I was asked the same question for c# here and I figured out by using linq you can do this easily.
But how can I simply do this since there is no alternative for linq in java?
I was asked the same question for c# here and I figured out by using linq you can do this easily.
But how can I simply do this since there is no alternative for linq in java?
If you want something similar to LINQ, you can do this using Java8 streams:
// prepare arrays
List<int[][]> kidsL = new ArrayList<>();
int[][] square1 = new int[8][8];
int[][] square2 = new int[8][8];
int[][] square3 = new int[8][8];
for (int i = 0; i < 8; i++)
for (int j = 0; j < 8; j++) {
square1[i][j] = 1;
square2[i][j] = 2;
square3[i][j] = 3;
}
kidsL.add(square1);
kidsL.add(square2);
kidsL.add(square3);
// find min
kidsL.stream()
.mapToInt(a -> Arrays.stream(a).flatMapToInt(Arrays::stream).sum())
.min()
.ifPresent(System.err::println);
// find max
kidsL.stream()
.mapToInt(a -> Arrays.stream(a).flatMapToInt(Arrays::stream).sum())
.max()
.ifPresent(System.err::println);
It prints:
64
192
But it is less effective than simple for loops, because you calculating the sum two times.
Of course you can add intermediate operation to store the list of sums, and then calculate min/max based on that.
// intermediate list of sums
List<Integer> sums = kidsL.stream()
.mapToInt(a -> Arrays.stream(a).flatMapToInt(Arrays::stream).sum())
.boxed().collect(Collectors.toList());
sums.stream().mapToInt(i -> i)
.min()
.ifPresent(System.err::println);
sums.stream().mapToInt(i -> i)
.max()
.ifPresent(System.err::println);
If the array is unsorted, the only real way to find the min and max is to iterate through the whole thing.
int[][] array = new int[10][10];
int min = array[0][0];
int max = array[0][0];
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[0].length; j++){
if(array[i][j] < min){
min = array[i][j];
}
if(array[i][j] > max){
max = array[i][j];
}
}
}
I just reread the question, and I think you mean an ArrayList<int[][]> which would be:
ArrayList<int[][]> arrayList = new ArrayList<int[][]>();
int min = arrayList.get(0)[0][0];
int max = arrayList.get(0)[0][0];
for(int[][] array : arrayList){
for(int i = 0; i < array.length; i++){
for(int j = 0; j < array[0].length; j++){
if(array[i][j] < min){
min = array[i][j];
}
if(array[i][j] > max){
max = array[i][j];
}
}
}
}
List.