Max value in array

Opposite of minimum value in array example, this example will find the greatest value present or max value in an array using java, java 8, guava and apache commons.

Setup

With straight up java we use a for loop to iterate over an array of numbers comparing each value to the previous. If the value is greater than the highest value, we will set the highest variable and proceed until we have looped over each element.

int[] numbers = {1, 24, 45, 62, 85, 8, 91, 3, 5, 56, 9};

Straight up Java

@Test
public void find_max_value_in_numeric_array_with_java () {

    int highest = numbers[0];
    for (int index = 1; index < numbers.length; index ++) {
        if (numbers[index] > highest) {
            highest = numbers [index];
        }
    }
    assertEquals(91, highest);
}

Java 8

Java 8 contains a number of stream reducing operations and the Stream.max operation is all we need to calculate the max value of an array. In the first set of code, we will convert the array to stream then call the Stream.max operation. It will return an OptionalInt describing the max value found or an empty OptionalInt if the stream is empty. The second code snippet will use IntStream, a specialized stream for dealing with primitive ints, calling the IntStream.max returning an OptionalInt which shares the same behavior as above. Looking for more than just the max, IntSummaryStatistics example is a class that calculates all statistics such as average, count, min max and sum.

@Test
public void find_max_value_in_numeric_array_with_java8 () {

    OptionalInt highest = Arrays.stream(numbers).max();

    assertEquals(91, highest.getAsInt());

    // or 

    OptionalInt highest2 = IntStream.of(numbers).max();

    assertEquals(91, highest2.getAsInt());
}

Google Guava

Guava's Ints class specialized in dealing with int primitives contains a Ints.max method which returns the greatest value present in array.

@Test
public void find_max_value_in_numeric_array_with_guava () {
    int highest = Ints.max(numbers);
    assertEquals(91, highest);
}

Apache Commons

Apache commons NumberUtils provides additional functionality to java numbers and contains NumberUtils.max which will return the maximum value in the passed in array.

@Test
public void find_max_value_in_array_with_apache_commons () {
    int highest = NumberUtils.max(numbers);
    assertEquals(91, highest);
}

ReactiveX - RXJava

Using the Observable.from method will convert the List to an Observable so it will emit the items to the sequence. Next, the max part of Mathematical and Aggregate Operators will find the maximum numeric value of the source returning a single item. If there is more than one item with the same value, the last one in the sequence will be returned.

@Test
public void find_max_value_in_array_with_rxjava() {

    Observable<Integer> findMax = Observable
            .from(Arrays.asList(1, 2, 3, 4));
    max(findMax).subscribe(System.out::println); // 4
}