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

前端 未结 15 1808
遥遥无期
遥遥无期 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: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
    

提交回复
热议问题