Java lambda 循環(huán)累加求和代碼
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); }
但是沒(méi)有BigDecimal類型,可以使用下面方法實(shí)現(xiàn)
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); }
補(bǔ)充知識(shí):Java算法——求1到100累加的和,3種循環(huán)
1、for循環(huán)
int sum = 0;for (int i = 1; i <= 100; i++) {sum += i;}System.out.println('1到100累加的和為:' + sum);
2、while循環(huán)
int sum = 0;int i = 1;while (i <= 100) {sum += i;i++;}System.out.println('1到100累加的和為:' + sum);
3、do...while循環(huán)
int sum = 0;int i = 1;do {sum += i;i++;} while (i <= 100);System.out.println('1到100累加的和為:' + sum);
以上這篇Java lambda 循環(huán)累加求和代碼就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Java進(jìn)行Appium自動(dòng)化測(cè)試的實(shí)現(xiàn)2. 詳細(xì)總結(jié)Java for循環(huán)的那些坑3. php中PHPUnit框架實(shí)例用法4. Python通過(guò)format函數(shù)格式化顯示值5. 新手學(xué)python應(yīng)該下哪個(gè)版本6. jsp文件下載功能實(shí)現(xiàn)代碼7. uni-app結(jié)合PHP實(shí)現(xiàn)單用戶登陸demo及解析8. 如何利用Python matplotlib繪制雷達(dá)圖9. ajax實(shí)現(xiàn)頁(yè)面的局部加載10. 詳解CSS偽元素的妙用單標(biāo)簽之美

網(wǎng)公網(wǎng)安備