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

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

    You could easily do it with an IntStream and the max() method.

    Example

    public static int maxValue(final int[] intArray) {
      return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
    }
    

    Explanation

    1. range(0, intArray.length) - To get a stream with as many elements as present in the intArray.

    2. map(i -> intArray[i]) - Map every element of the stream to an actual element of the intArray.

    3. max() - Get the maximum element of this stream as OptionalInt.

    4. getAsInt() - Unwrap the OptionalInt. (You could also use here: orElse(0), just in case the OptionalInt is empty.)

提交回复
热议问题