java8 reduce

https://blog.csdn.net/qq564425/article/details/81536771

List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7);
int sum = 0;
for(Integer integer:nums) {
    sum+=integer;
}
System.out.println(sum);//28

The following is the sum operation of the stream operation:

List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7);
int sum = nums.stream().reduce(0, (a,b)->a+b);
System.out.println(sum);//28

Explain the meaning of the above code:

reduce accepts two parameters:

  • An initial value, here is 0;

  • A BinaryOperator to combine two elements to produce a new value, here we use lambda(a, b) -> a + b.

You can also use method references to make the code more concise:

int sum = nums.stream().reduce(0, Integer::sum);

In addition, reduce also has an overloaded method, which has no initial value and uses Optional to receive the result:

List<Integer> nums = Arrays.asList(1,2,3,4,5,6,7);
Optional<Integer> optional = nums.stream().reduce(Integer::sum);
System.out.println(optional.get());//28

When there is no value in the list, an error will be reported.

List<Integer> nums = Arrays.asList();
Optional<Integer> optional = nums.stream().reduce(Integer::sum);
System.out.println(optional.get());
Exception in thread "main" java.util.NoSuchElementException: No value present
	at java.util.Optional.get(Optional.java:135)
	at list_demo.orElseOrElseGetComparation.main(orElseOrElseGetComparation.java:3)

Guess you like

Origin blog.csdn.net/yangyangrenren/article/details/114695307