总结所有元素java arraylist

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16242733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:58:48  来源:igfitidea点击:

Sum all the elements java arraylist

javaarraylistsum

提问by

If I had: ArrayList<Double> m = new ArrayList<Double>();with the double values ??inside, how should I do to add up all the ArrayList elements?

如果我有:ArrayList<Double> m = new ArrayList<Double>();在里面有双精度值,我应该怎么做才能把所有的 ArrayList 元素加起来?

public double incassoMargherita()
{
 double sum = 0;
 for(int i = 0; i < m.size(); i++)
 {          
 }
 return sum;
}

as?

作为?

采纳答案by Barranka

Two ways:

两种方式:

Use indexes:

使用索引:

double sum = 0;
for(int i = 0; i < m.size(); i++)
    sum += m.get(i);
return sum;

Use the "for each" style:

使用“for each”样式:

double sum = 0;
for(Double d : m)
    sum += d;
return sum;

回答by TheEwook

Not very hard, just use m.get(i)to get the value from the list.

不是很难,只是用来m.get(i)从列表中获取值。

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum += m.get(i);
    }
    return sum;
}

回答by j.jerrod.taylor

I haven't tested it but it should work.

我还没有测试过,但它应该可以工作。

public double incassoMargherita()
{
    double sum = 0;
    for(int i = 0; i < m.size(); i++)
    {
        sum = sum + m.get(i);
    }
    return sum;
}

回答by Lokeshkumar R

Using Java 8 streams:

使用 Java 8

double sum = m.stream()
    .mapToDouble(a -> a)
    .sum();

System.out.println(sum); 

回答by Mikhail Kholodkov

Java 8+ version for Integer, Long, Doubleand Float

Java的8+版本IntegerLongDoubleFloat

    List<Integer> ints = Arrays.asList(1, 2, 3, 4, 5);
    List<Long> longs = Arrays.asList(1L, 2L, 3L, 4L, 5L);
    List<Double> doubles = Arrays.asList(1.2d, 2.3d, 3.0d, 4.0d, 5.0d);
    List<Float> floats = Arrays.asList(1.3f, 2.2f, 3.0f, 4.0f, 5.0f);

    long intSum = ints.stream()
            .mapToLong(Integer::longValue)
            .sum();

    long longSum = longs.stream()
            .mapToLong(Long::longValue)
            .sum();

    double doublesSum = doubles.stream()
            .mapToDouble(Double::doubleValue)
            .sum();

    double floatsSum = floats.stream()
            .mapToDouble(Float::doubleValue)
            .sum();

    System.out.println(String.format(
            "Integers: %s, Longs: %s, Doubles: %s, Floats: %s",
            intSum, longSum, doublesSum, floatsSum));

15, 15, 15.5, 15.5

15、15、15.5、15.5