Finding the max/min value in an array of primitives using Java

前端 未结 15 1811
遥遥无期
遥遥无期 2020-11-22 05:09

It\'s trivial to write a function to determine the min/max value in an array, such as:

/**
 * 
 * @param chars
 * @return the max value in the array of chars         


        
相关标签:
15条回答
  • 2020-11-22 05:30

    The basic way to get the min/max value of an Array. If you need the unsorted array, you may create a copy or pass it to a method that returns the min or max. If not, sorted array is better since it performs faster in some cases.

    public class MinMaxValueOfArray {
        public static void main(String[] args) {
            int[] A = {2, 4, 3, 5, 5};
            Arrays.sort(A);
            int min = A[0];
            int max = A[A.length -1];
            System.out.println("Min Value = " + min);        
            System.out.println("Max Value = " + max);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 05:36

    A solution with reduce():

    int[] array = {23, 3, 56, 97, 42};
    // directly print out
    Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);
    
    // get the result as an int
    int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
    System.out.println(res);
    >>
    97
    97
    

    In the code above, reduce() returns data in Optional format, which you can convert to int by getAsInt().

    If we want to compare the max value with a certain number, we can set a start value in reduce():

    int[] array = {23, 3, 56, 97, 42};
    // e.g., compare with 100
    int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
    System.out.println(max);
    >>
    100
    

    In the code above, when reduce() with an identity (start value) as the first parameter, it returns data in the same format with the identity. With this property, we can apply this solution to other arrays:

    double[] array = {23.1, 3, 56.6, 97, 42};
    double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
    System.out.println(max);
    >>
    97.0
    
    0 讨论(0)
  • 2020-11-22 05:38
        public int getMin(int[] values){
            int ret = values[0];
            for(int i = 1; i < values.length; i++)
                ret = Math.min(ret,values[i]);
            return ret;
        }
    
    0 讨论(0)
提交回复
热议问题