1. 程式人生 > 程式設計 >Java lambda 迴圈累加求和程式碼

Java lambda 迴圈累加求和程式碼

java 8 stream 提供了下面幾種型別的求和

Stream::mapToInt

Stream::mapToDouble

Stream::mapToLong

 public void test() {
 List<Person> people = new ArrayList<>();
 people.add(new Person("zhangsan",20));
 people.add(new Person("lisi",26));
 people.add(new Person("wangwu",35));
 
 int sum = people.stream()
      .mapToInt(p -> p.getAge())
      .sum();
 System.out.println("Total of ages " + sum);
 }

但是沒有BigDecimal型別,可以使用下面方法實現

  public void test() {
 List<Person> list = new ArrayList<>();
 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累加的和為:" + sum);

3、do...while迴圈

int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 100);
System.out.println("1到100累加的和為:" + sum);

以上這篇Java lambda 迴圈累加求和程式碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。