对列表里某个类中的某个属性进行求和操作非常常见。在Java 8诞生前,常用for循环手动累加,往往要写上三四行代码,不够简练。
参考链接
比如有个类:
class Hhd{
private String aStr;
private double bDou;
public String getaStr() {
return aStr;
}
public void setaStr(String aStr) {
this.aStr = aStr;
}
public double getbDou() {
return bDou;
}
public void setbDou(double bDou) {
this.bDou = bDou;
}
}
求和操作一行代码便可完成,并且有一下四种方式,挑喜欢的就好~:
@Test
public void TestStreamSum() {
Hhd a = new Hhd();
a.setbDou(1.);
Hhd b = new Hhd();
b.setbDou(233.);
List<Hhd> aList = new ArrayList<>();
aList.add(a);
aList.add(b);
double allSum = aList.stream().map(Hhd::getbDou).reduce(0., Double::sum);
double allSum_1 = aList.stream().map(Hhd::getbDou).reduce(0., (x, y) -> x + y);
double allSum_2 = aList.stream().collect(Collectors.summingDouble(Hhd::getbDou));
double allSum_3 = aList.stream().mapToDouble(Hhd::getbDou).sum();
System.out.println(allSum);
System.out.println(allSum_1);
System.out.println(allSum_2);
System.out.println(allSum_3);
}