Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce Integer.min doesn't return lowest element

Tags:

java

java-8

I am doing some research on the stream reduce and trying to run the very simple program.

Why Integer.min doesn't return the minimum number like Integer.min return the maximum number ?

public class Reducing {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(3,4,5,1,2);
        Integer sum = numbers.stream().reduce(0, (a, b) -> a+ b);
        System.out.println("REDUCE : "+sum);

        int sum2 = numbers.stream().reduce(0, Integer::sum);
        System.out.println(sum2);

        int max = numbers.stream().reduce(0, (a, b) -> Integer.max(a, b));
        System.out.println("MAX == > "+max);

        int min = numbers.stream().reduce(0, (a, b) -> Integer.min(a, b));
        System.out.println("MIN == > "+min);
    }
}

Output ==>

REDUCE : 15
15
MAX == > 5
MIN == > 0
like image 362
PAA Avatar asked Oct 26 '17 19:10

PAA


3 Answers

You are supplying 0 as identity item to min. This value will also used in computations.

int min = numbers.stream().reduce(0, (a, b) -> Integer.min(a, b));

So virtually it is like having

Arrays.asList(0,3,4,5,1,2)

You shuold omit the identity element in your example

int min = numbers.stream().reduce((a, b) -> Integer.min(a, b)).get();
like image 141
Aleh Maksimovich Avatar answered Oct 16 '22 17:10

Aleh Maksimovich


You're passing 0 as the initial value into your reduce: reduce(0, (a, b) -> Integer.min(a, b)). It's therefore the smallest number. Pass Integer.MAX_VALUE instead or use the following:

Optional<Integer> min = numbers.stream().reduce((a, b) -> Integer.min(a, b));
System.out.println("MIN == > " + min.get());

Or, an even without the lambda:

Optional<Integer> min = numbers.stream().reduce(Integer::min)

There's also an option of doing it reduce.and using min instead:

Optional<Integer> min = numbers.stream().min(Comparator.naturalOrder());
like image 22
Malt Avatar answered Oct 16 '22 17:10

Malt


the reduce operation works as: you have this list:

Arrays.asList(3,4,5,1,2); 

and do

reduce(0, (a, b) -> Integer.max(a, b));

which means:

compare all the pair a, b and the first element must 0 as precesor

so the operation will be

Integer.max(a, b)
Integer.max(0, 3) => return  3
Integer.max(3, 4) => return  4
Integer.max(4, 5) => return  5
Integer.max(5, 1) => return  5
Integer.max(5, 2) => return  5

and for the min, the same analogy applies...

Integer.min(a, b)

Integer.min(0, 3) => return  0
Integer.min(0, 4) => return  0
Integer.min(0, 5) => return  0
Integer.min(0, 1) => return  0
Integer.min(0, 2) => return  0

thus the result max:5 and min:0

like image 43
ΦXocę 웃 Пepeúpa ツ Avatar answered Oct 16 '22 16:10

ΦXocę 웃 Пepeúpa ツ