53

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?

Augustus
  • 1,479
  • 2
  • 17
  • 31

8 Answers8

66

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;
Community
  • 1
  • 1
Barranka
  • 20,547
  • 13
  • 65
  • 83
  • 6
    or Use : JAVA 8 int sum = list.stream().mapToInt(Integer::intValue).sum(); – Anand Varkey Philips Sep 04 '17 at 10:33
  • 1
    @AnandVarkeyPhilips that's like using a nuke to kill a fly :P – Barranka Sep 04 '17 at 14:21
  • 2
    Why do you think it is?? Does it cause Performance Degradation?? Less and Clean Code, I was hoping for! – Anand Varkey Philips Sep 04 '17 at 19:41
  • 3
    @AnandVarkeyPhilips The `:P` on the end of comment by Barranka means she/he was joking, or half-joking. See [Emoticons list](https://en.wikipedia.org/wiki/List_of_emoticons): *Tongue sticking out, cheeky/playful, blowing a raspberry*. – Basil Bourque Apr 19 '18 at 04:36
  • 1
    @AnandVarkeyPhilips I didn't mean to offend you in any way, nor I think your solution is incorrect. Your answer *is* correct, and I was merely joking (thanks to BasilBourque for pointing it out) – Barranka Apr 19 '18 at 05:39
  • 1
    lol... i was learning streams and thought it will be helpful for someone reading this here... then your comment made me think that it will create some performance degradation.. I did'nt know.. that's why I asked.. :) – Anand Varkey Philips Apr 20 '18 at 12:08
36

Using Java 8 streams:

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

System.out.println(sum); 
Mario Cianciolo
  • 1,223
  • 10
  • 17
Lokeshkumar R
  • 575
  • 5
  • 13
  • what is a in that? – Cyph3rCod3r Sep 03 '18 at 18:35
  • 2
    `a -> a` is a lambda function. Before the arrow is the parameter list (a) after the arrow is the body of the function (a). It's roughly equivalent to `double identity(double a) { return a }` – cmc Oct 10 '18 at 19:05
14

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

Mikhail Kholodkov
  • 23,642
  • 17
  • 61
  • 78
9

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;
}
j.jerrod.taylor
  • 1,120
  • 1
  • 13
  • 33
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;
}
TheEwook
  • 11,037
  • 6
  • 36
  • 55
2

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);
}
Aman Kumar
  • 41
  • 4
0

Try this

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

I see that it is very old question but why did nobody offer easiest way without loop?

sum = m.sum()
Kirguduck
  • 748
  • 1
  • 9
  • 20