Flask接口签名sign原理与实例代码浅析
528
2022-11-27
Java lambda 循环累加求和代码
java 8 stream 提供了下面几种类型的求和
Stream::mapToInt
Stream::mapToDouble
Stream::mapToLong
public void test() {
List
people.add(new Person("zhangsan",20));
people.add(new Person("lisi", 26));
people.add(new Person("wangwu",35));
int sum = people.stream()
.mapTohttp://Int(p -> p.getAge())
.sum();
System.out.println("Total of ages " + sum);
}
但是没有BigDecimal类型,可以使用下面方法实现
public void test() {
List
list.add(new Person("zhangsan", 20, new BigDecimal(10.5)));
list.add(new Person("lisi", 26, new BigDecimal(22.2)));
list.add(new Person("wangwu", 35, new BigDecimal(15.54)));
BigDecimal amounts = list.stream().map(item -> item.getAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add);
amounts = amounts.setScale(1, BigDecimal.ROUND_DOWN);
System.out.println("Total of amounts:" + amounts);
// 或者
BigDecimal sum = list
.stream()
.map(Person::getAmount)
.reduce(BigDecimal::add)
.get();
sum = sum.setScale(1, BigDecimal.ROUND_DOWN);
System.out.println("Total of sums: " + sum);
}
补充知识:Java算法——求1到100累加的和,3种循环
1、for循环
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
System.out.println("1到100累加的和为:" + sum);
2、while循环
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
System.out.println("1到100累加YUOJNl的和为:" + sum);
3、do...while循环
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("1到100累加的和为:" + sum);
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~