Min value in array

Opposite of maximum value in array example, this example will find the lowest or minimum value in array using java, java 8, guava and apache commons.

Setup

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

Straight up Java

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 less than the lowest value, we will set the lowest variable and proceed until we have looped over each element.

@Test
public void find_min_value_in_numeric_array_with_java () {

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

Java 8

Java 8 contains a number of stream reduction operations and the Stream.min operation is what we need to find the min value of an array. In the first set of code, we will transform the array to stream then call the Stream.min operation. It will return an OptionalInt describing the min 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.min returning an OptionalInt which shares the same behavior as above. Looking for more than just the min, IntSummaryStatistics is a class that calculates all statistics such as average, count, min max and sum.

@Test
public void find_min_value_in_numeric_array_with_java8 () {

    OptionalInt lowest = Arrays.stream(numbers).min();

    assertEquals(1, lowest.getAsInt());

    // or 

    OptionalInt lowest2 = IntStream.of(numbers).min();

    assertEquals(1, lowest2.getAsInt());
}

Google Guava

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

@Test
public void find_min_value_in_numeric_array_with_guava () {
    int lowest = Ints.min(numbers);
    assertEquals(1, lowest);
}

Apache Commons

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

@Test
public void find_min_value_in_array_with_apache_commons () {
    int lowest = NumberUtils.min(numbers);
    assertEquals(1, lowest);
}

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 min, part of Mathematical and Aggregate Operators, will find the minimum 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_min_value_in_array_with_rxjava() {

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