java8stream对List求和⽅法总结
主要利⽤了reduce⽅法和Collectors.summing的⽅法,reduce根据初始值(参数1)和累积函数(参数2)依次对数据流进⾏操作,第⼀
个值与初始值送⼊累积函数,后⾯计算结果和下⼀个数据流依次送⼊累积函数实现求和,Collectors.summingXXX()(XXX表⽰具体数据
类型)将流中所有元素视为Long类型,并计算所有元素的总和,下⾯直接给⼀个实例:
import java.util.ArrayList;
import java.util.Collection;
java streamimport java.util.Collections;
import java.util.List;
import urrent.Callable;
import urrent.ExecutionException;
import urrent.FutureTask;
import java.util.stream.Collectors;
public class java_list_sum_test {
public static class Person {
int age;
Person (int age) {
this.age = age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
List<Long> testList = new ArrayList<>(Collections.nCopies(5, 0L));
testList.set(0,1L);
testList.set(1,2L);
testList.set(2,3L);
testList.set(3,4L);
testList.set(4,5L);
System.out.println("sum1 is " + testList.stream().reduce(0L, (a, b) -> a + b));
// reduce根据初始值(参数1)和累积函数(参数2)依次对数据流进⾏操作,第⼀个值与初始值送⼊累积函数,后⾯计算结果和下⼀个数据流依次送⼊累积函数。 System.out.println("sum2 is " + testList.stream().reduce(0L, Long::sum));
System.out.println("sum3 is " + testList.stream().collect(Collectors.summingLong(Long::longValue)));
// Collectors.summingLong()将流中所有元素视为Long类型,并计算所有元素的总和
System.out.println("sum4 is " + testList.stream().mapToLong(Long::longValue).sum());
System.out.println("***********************");
List<Person> testList1 = new ArrayList<>(Collections.nCopies(5, new Person(1)));
System.out.println("class sum1 is " + testList1.stream().map(e -> e.getAge()).reduce(0, (a,b) -> a + b));
System.out.println("class sum2 is " + testList1.stream().map(e -> e.getAge()).reduce(0, Integer::sum));
System.out.println("class sum3 is " + testList1.stream().collect(Collectors.summingInt(Person::getAge)));
System.out.println("class sum4 is " + testList1.stream().map(e -> e.getAge()).mapToInt(Integer::intValue).sum());
return;
}
}
执⾏结果如下:
sum1 is 15
sum2 is 15
sum3 is 15
sum4 is 15
*********************** class sum1 is 5 class sum2 is 5 class sum3 is 5 class sum4 is 5
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论