Search code examples
javaarraysjava-streamoption-type

How do I compare the minimum values in the list?


I'm trying to compare the minimal values of two arrays.

I'm getting the following compilation error:

Operator '>' cannot be applied to 'java.util.OptionalInt', 'java.util.OptionalInt'

What am I doing wrong?

My code:

public static void main(String[] args) { 

    int [] ints = {12,6,8,242}; 

    int [] ints1 = {5,1,5432,5,76,146,8}; 

    if(Arrays.stream(ints).min()>Arrays.stream(ints1).min()){ 

        System.out.println(Arrays.stream(ints1).min()); 

    } 

} 

Solution

  • min() retrieves OptionalInt. So to get a primitive int you have to call getAsInt():

    int[] one = { 12, 6, 8, 242 };
    int[] two = { 5, 1, 5432, 5, 76, 146, 8 };
    
    if (Arrays.stream(one).min().getAsInt() > Arrays.stream(two).min().getAsInt())
        System.out.println(Arrays.stream(two).min().getAsInt());
    

    Another option is to use Apache:

    import org.apache.commons.lang.math.NumberUtils;
    
    int[] one = { 12, 6, 8, 242 };
    int[] two = { 5, 1, 5432, 5, 76, 146, 8 };
    
    if (NumberUtils.min(one) > NumberUtils.min(two))
        System.out.println(NumberUtils.min(two));