简体   繁体   中英

Sum all the elements java arraylist

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?

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

as?

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:

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

Using Java 8 streams :

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

System.out.println(sum); 

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;
}

Java 8+ version for Integer , Long , Double and Float

    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

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

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

You can even leverage the power of reduce of stream . In Java 8, the Stream.reduce() combine elements of a stream and produces a single value.

public double incassoMargherita()
{
    // reduce takes 2 args => 
    // 1. initial value
    // 2. binary operator
    return m.stream().reduce(0, (a,b) -> a + b);
}

Try this

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

我看到这是一个非常古老的问题,但为什么没有人提供没有循环的最简单方法?

sum = m.sum()
double sumTransaction = transactionList.stream().mapToDouble(a -> a.getApacAmount()).sum();
System.out.println(sumTransaction); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM