Get the smallest element in a specific row or column in a 2nd array

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().

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=142790&siteId=1