美文网首页
Groovy: 对Collection进行sum操作

Groovy: 对Collection进行sum操作

作者: 溺水的鱼_f3bd | 来源:发表于2017-06-01 11:33 被阅读0次

在Groovy里, 如果要对一个Collection或数组里的元素求和,只需要调用一下sum方法既可

def list = [1,2,3,4,5,6,7,8];
println list.sum(); // Output:36
println list.sum(10); // Output:46

sum可以有参数, 也可以没有参数。 有参数的话参数也会被记入总和。

不仅仅是数值类型的collection可以进行求和运算, 实现了plus方法的类的集合也可以:
class Person {
String name;
BigInteger salary;

Person plus(Person that){
    return new Person(salary: this.salary + that.salary)
}

}

def persons = [
new Person(salary:1000, name:"Tom"),
new Person(salary:2000, name:"Sam"),
new Person(salary:3000, name:"Kim")
];

println persons.sum().salary // Output: 6000
println persons.sum {it.salary} // Output: 6000
println persons*.salary.sum() // Output: 6000
原文链接:http://www.myexception.cn/program/1304712.html

相关文章

网友评论

      本文标题:Groovy: 对Collection进行sum操作

      本文链接:https://www.haomeiwen.com/subject/otnsfxtx.html