Java – how to use reduce only to find the minimum value in the list?

I want to use reduce only to find the minimum value in list < integer > This is my original idea:

List<Integer> lst;
//init
//assuming it's not empty
lst.stream().reduce(lst.get(0),(x,y) -> x.compareTo(y) <= 0  ? x : y);

But in the contract method, it says:

Therefore, the only possible identity value retains the contract of the accumulator (x, y) – > x.compareto (y) < = 0? x: Y is the maximum So we have some egg problems How to solve it and keep all contracts?

Solution

Use integer MAX_ VALUE. Everything else will be less than or equal to, so it satisfies all the contracts of min (identity, t) = = t

After further study, I don't think you need this identity One simplification is to take the function as an argument, http://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#reduce -java. util. function. BinaryOperator-. This will return optional < integer > instead of an integer I believe the reason is that the method must deal with the absence of elements in the stream In this case, optional < integer > version will return a null value; Although the version that requires an identifier and returns an integer will return the identifier value (similar to mathematics, if you add a set of numbers and it is empty, you should get 0, if you multiply a set of numbers and it is empty, you should get 1) So if you know your list is not empty, you should actually be able to write

lst.stream().reduce((x,y) -> x.compareTo(y) <= 0  ? x : y).get();
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>