Java get the maximum value of an array

Briefly

There are actually many ways. I will put some first, and then I will put it up when I encounter the corresponding code.

The easiest is of course to find a way to compare them one by one~ Of course, there are still some interesting operations

Example one:

import java.util.Arrays;	
	
    public static int MAX(int[] arr) {
        Arrays.sort(arr);
        return arr[arr.length-1];
    }

is to sort first and then get the result

Example 2
This is a code from the rookie tutorial

import java.util.Arrays;
import java.util.Collections;
 
public class Main {
    public static void main(String[] args) {
        Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};
        int min = (int) Collections.min(Arrays.asList(numbers));
        int max = (int) Collections.max(Arrays.asList(numbers));
        System.out.println("最小值: " + min);
        System.out.println("最大值: " + max);
    }
}

Example three:

import java.util.Arrays
	public static int MAX(int[] arr) {
        return Arrays.stream(arr).max().getAsInt();
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324136869&siteId=291194637