草庐IT

Java BigDecimal、Integer、Long、Double类型数值累加求和

lfwh 2023-04-22 原文

文章目录

1 BigDecimal类型数值累加求和

1.1 for循环实现

List<BigDecimal> list=new ArrayList<>();
BigDecimal sum=new BigDecimal(0);
for(BigDecimal decimal:list){
    sum=sum.add(decimal);
}

1.2 stream().reduce()实现

List<BigDecimal> list=new ArrayList<>();
BigDecimal sum=list.stream().reduce(0,BigDecimal::add);

2 Integer类型数值累加求和

2.1 for循环实现

List<Integer> list=new ArrayList<>();
Integer sum=0;
for(Integer i:list){
    sum+=i;
}

2.2 stream().reduce()实现

List<Integer> list=new ArrayList<>();
//lambda表达式实现
Integer sum = list.stream().reduce(0, (current, number) -> current + number);
//方法引用实现
Integer sum2 = list.stream().reduce(0, Integer::sum); 

2.3 Collectors.summingInt()实现

List<Integer> list=new ArrayList<>();
long sum = list.stream().collect(Collectors.summingInt(x -> x));

2.4 Collectors.summarizingInt()实现

        List<Integer> list = new ArrayList<>();
        IntSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingInt(x -> x));
        long sum = summaryStatistics.getSum(); 

3 Long类型数值累加求和

3.1 for循环实现

List<Long> list=new ArrayList<>();
Long sum=0L;
for(Long i:list){
    sum+=i;
}

3.2 stream().reduce()实现

List<Long> list=new ArrayList<>();
//lambda表达式实现
Long sum = list.stream().reduce(0L, (current, number) -> current + number);
//方法引用实现
Long sum2 = list.stream().reduce(0L, Long::sum); 

3.3 Collectors.summingLong()实现

List<Long> list=new ArrayList<>();
long sum = list.stream().collect(Collectors.summingLong(x -> x));

3.4 Collectors.summarizingInt()实现

        List<Long> list = new ArrayList<>();
        LongSummaryStatistics summaryStatistics = list.stream().collect(Collectors.summarizingLong(x -> x));
        long sum = summaryStatistics.getSum();

4 Double类型数值累加求和

4.1 for循环实现

List<Double> list = new ArrayList<>();
Double sum = 0d;
for (Double i : list) {
    sum += i;
}

注意 Double小数点失真问题解决 : 先把Double转为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转BigDecimal类型


总结

如果此篇文章有帮助到您, 希望打大佬们能关注点赞收藏评论支持一波,非常感谢大家!
如果有不对的地方请指正!!!

参考1

有关Java BigDecimal、Integer、Long、Double类型数值累加求和的更多相关文章

  1. ruby-on-rails - 如果为空或不验证数值,则使属性默认为 0 - 2

    我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val

  2. ruby - Infinity 和 NaN 的类型是什么? - 2

    我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串

  3. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  4. ruby - Ruby 有 `Pair` 数据类型吗? - 2

    有时我需要处理键/值数据。我不喜欢使用数组,因为它们在大小上没有限制(很容易不小心添加超过2个项目,而且您最终需要稍后验证大小)。此外,0和1的索引变成了魔数(MagicNumber),并且在传达含义方面做得很差(“当我说0时,我的意思是head...”)。散列也不合适,因为可能会不小心添加额外的条目。我写了下面的类来解决这个问题:classPairattr_accessor:head,:taildefinitialize(h,t)@head,@tail=h,tendend它工作得很好并且解决了问题,但我很想知道:Ruby标准库是否已经带有这样一个类? 最佳

  5. ruby - 查找字符串中的内容类型(数字、日期、时间、字符串等) - 2

    我正在尝试解析一个CSV文件并使用SQL命令自动为其创建一个表。CSV中的第一行给出了列标题。但我需要推断每个列的类型。Ruby中是否有任何函数可以找到每个字段中内容的类型。例如,CSV行:"12012","Test","1233.22","12:21:22","10/10/2009"应该产生像这样的类型['integer','string','float','time','date']谢谢! 最佳答案 require'time'defto_something(str)if(num=Integer(str)rescueFloat(s

  6. ruby-on-rails - 在 Rails 开发环境中为 .ogv 文件设置 Mime 类型 - 2

    我正在玩HTML5视频并且在ERB中有以下片段:mp4视频从在我的开发环境中运行的服务器很好地流式传输到chrome。然而firefox显示带有海报图像的视频播放器,但带有一个大X。问题似乎是mongrel不确定ogv扩展的mime类型,并且只返回text/plain,如curl所示:$curl-Ihttp://0.0.0.0:3000/pr6.ogvHTTP/1.1200OKConnection:closeDate:Mon,19Apr201012:33:50GMTLast-Modified:Sun,18Apr201012:46:07GMTContent-Type:text/plain

  7. ruby - 为什么 Integer.respond_to?( :even? ) 返回 false? - 2

    我一直在研究RubyKoans,我发现about_open_classes.rbkoan很有趣。特别是他们修改Integer#even?方法的最后一个测试。我想尝试一下这个概念,所以我打开了Irb并尝试运行Integer.respond_to?(:even?),但令我惊讶的是我得到了错误。然后我尝试了Fixnum.respond_to?(:even?)并得到了错误。我还尝试了Integer.respond_to?(:respond_to?)并得到了true,当我执行2.even?时,我也得到了true。我不知道发生了什么。谁能告诉我缺少什么? 最佳答案

  8. ruby 正则表达式 : replace double slashes in URL - 2

    除了协议(protocol)定义中的斜杠('http[s]://'、'ftp://'等)之外,我想替换URL中的所有多个斜杠。我该怎么做?此代码无一异常(exception)地替换:url.gsub(/\/\/+/,'/') 最佳答案 您只需排除任何以:开头的匹配项url.gsub(/([^:])\/\//,'\1/') 关于ruby正则表达式:replacedoubleslashesinURL,我们在StackOverflow上找到一个类似的问题: http

  9. ruby-on-rails - Rails 迁移中的 PostgreSQL 点类型 - 2

    我想使用PostgreSQL中的point类型。我已经完成了:railsgmodelTestpoint:point最终的迁移是:classCreateTests当我运行时:rakedb:migrate结果是:==CreateTests:migrating====================================================--create_table(:tests)rakeaborted!Anerrorhasoccurred,thisandalllatermigrationscanceled:undefinedmethod`point'for#/hom

  10. ruby-on-rails - 我可以用鸭子类型(duck typing)改进这种方法吗? - 2

    希望我没有误解“ducktyping”的含义,但从我读到的内容来看,这意味着我应该根据对象如何响应方法而不是它是什么类型/类来编写代码。代码如下:defconvert_hash(hash)ifhash.keys.all?{|k|k.is_a?(Integer)}returnhashelsifhash.keys.all?{|k|k.is_a?(Property)}new_hash={}hash.each_pair{|k,v|new_hash[k.id]=v}returnnew_hashelseraise"CustomattributekeysshouldbeID'sorPropertyo

随机推荐