1 BigDecimal類型數(shù)值累加求和
1.1 for循環(huán)實(shí)現(xiàn)
List<BigDecimal> list=new ArrayList<>();
BigDecimal sum=new BigDecimal(0);
for(BigDecimal decimal:list){
sum=sum.add(decimal);
}
1.2 stream().reduce()實(shí)現(xiàn)
List<BigDecimal> list=new ArrayList<>();
BigDecimal sum=list.stream().reduce(0,BigDecimal::add);
2 Integer類型數(shù)值累加求和
2.1 for循環(huán)實(shí)現(xiàn)
List<Integer> list=new ArrayList<>();
Integer sum=0;
for(Integer i:list){
sum+=i;
}
2.2 stream().reduce()實(shí)現(xiàn)
List<Integer> list=new ArrayList<>();
//lambda表達(dá)式實(shí)現(xiàn)
Integer sum = list.stream().reduce(0, (current, number) -> current + number);
//方法引用實(shí)現(xiàn)
Integer sum2 = list.stream().reduce(0, Integer::sum);
2.3 Collectors.summingInt()實(shí)現(xiàn)
List<Integer> list=new ArrayList<>();
long sum = list.stream().collect(Collectors.summingInt(x -> x));
2.4 Collectors.summarizingInt()實(shí)現(xiàn)
List<Integer> list = new ArrayList<>();
IntSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingInt(x -> x));
long sum = summaryStatistics.getSum();
3 Long類型數(shù)值累加求和
3.1 for循環(huán)實(shí)現(xiàn)
List<Long> list=new ArrayList<>();
Long sum=0L;
for(Long i:list){
sum+=i;
}
3.2 stream().reduce()實(shí)現(xiàn)
List<Long> list=new ArrayList<>();
//lambda表達(dá)式實(shí)現(xiàn)
Long sum = list.stream().reduce(0L, (current, number) -> current + number);
//方法引用實(shí)現(xiàn)
Long sum2 = list.stream().reduce(0L, Long::sum);
3.3 Collectors.summingLong()實(shí)現(xiàn)
List<Long> list=new ArrayList<>();
long sum = list.stream().collect(Collectors.summingLong(x -> x));
3.4 Collectors.summarizingInt()實(shí)現(xiàn)
List<Long> list = new ArrayList<>();
LongSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingLong(x -> x));
long sum = summaryStatistics.getSum();
4 Double類型數(shù)值累加求和
4.1 for循環(huán)實(shí)現(xiàn)
List<Double> list = new ArrayList<>();
Double sum = 0d;
for (Double i : list) {
sum += i;
}
注意 Double小數(shù)點(diǎn)失真問(wèn)題解決 : 先把Double轉(zhuǎn)為BigDecimal,再求和。代碼如下 :
List<Double> list = new ArrayList<>();
list.add(1.24224D);
list.add(1.24224D);
list.add(1.32224D);
BigDecimal bSum = new BigDecimal(0);
for (Double i : list) {
bSum = bSum.add(BigDecimal.valueOf(i));
}
System.out.println(bSum.doubleValue());
5 BigDecimal工具類
6 Object轉(zhuǎn)BigDecimal類型
總結(jié)
如果此篇文章有幫助到您, 希望打大佬們能
關(guān)注
、點(diǎn)贊
、收藏
、評(píng)論
支持一波,非常感謝大家!
如果有不對(duì)的地方請(qǐng)指正!!!文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-787578.html
參考1文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-787578.html
到了這里,關(guān)于Java BigDecimal、Integer、Long、Double類型數(shù)值累加求和的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!