The Creeper :
I'm wondering how might to get the smallest element in a specific row of a 2nd array in java.
I have tried arrays.sort but it doesn't work like expected.
this is what I have :
static int largestinrow(int[][] arr, int row){
int nums = arrays.sort(arr[row]);
return nums;
}
Samuel Philipp :
You can use Arrays.stream()
and IntStream.min()
:
static int smallestinrow(int[][] arr, int row){
return Arrays.stream(arr[row])
.min()
.orElseThrow(IllegalArgumentException::new);
}
To get the smallest number in the whole 2d array you can use:
static int smallest(int[][] arr){
return Arrays.stream(arr)
.flatMapToInt(Arrays::stream)
.min()
.orElseThrow(IllegalArgumentException::new);
}
If you want to return a default value for an empty array, instead of throwing an exception you can use .orElse()
instead of .orElseThrow()
.