Sum of the Elements Arraylist

Sum all the elements java arraylist

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;

Sum of the elements ArrayList

Declare numbers as ArrayList<Integer> numbers.
Then the Integer will be unboxed to int. Right now, your arraylist contains objects that may not be ints.

For the moment, numbers.get() will return an object, and you can not add an object to an int directly.

You could always cast the element to Integer, but I would recommend the first option.

How do I sum the elements of an array list?

    double n1 = 1, n2 = 3, result, sum = 0;     
ArrayList<Double> list = new ArrayList<>();

while( n2 <= 99) {
result = n1/n2;
list.add(result);
n2 += 2;
}

for(double temp: list)
sum = sum + temp;

System.out.println(sum); //1.9377748484749076

If you put the for loop inside while you get

double n1 = 1, n2 = 3, result, sum = 0;     
ArrayList<Double> list = new ArrayList<>();

while( n2 <= 99) {
result = n1/n2;
list.add(result);
n2 += 2;

for(double temp: list)
sum = sum + temp;
}
System.out.println(sum); //73.35762984798366

Sum of an arrayList

You can use this code snippet: (Written in kotlin)

fun main() {
val s: List<Float> = listOf(1.2F, 1.4F, 5.6F)
// populate it with your custom list data
var sum = 0F

s.forEach { it ->
sum+=it
}
println("Sum = $sum and avg = ${sum/(s.size)}")

}

Well here is the java solution:

class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
List<Float> s = new ArrayList(Arrays.asList(1.2F, 1.3F, 5.4F, 6.5F));
Float sum = 0F;

for (int i=0; i< s.size(); i++) {
sum+=s.get(i);
}

System.out.println("Sum: "+sum+" and Avg: "+sum/(s.size()));
}
}

Get the sum of elements of an ArrayList

To get the sum of the elements as your question states, you can use streams.

int sum = history.stream()
.filter(his->his.getRes().equals("Vundet"))
.mapToInt(his->his.getWins()) // assuming this getter exists.
.sum();

How to sum up all the elements with the same property in an ArrayList in Java?

You can do this with streams:

import static java.util.stream.Collectors.*;

...

Map<String, Integer> map = items.stream()
.collect(groupingBy(Item::getCode,
summingInt(Item::getQuantity)));

Assuming your class has these getters:

public class Item {
...
public String getCode() {...}
public int getQuantity() {...}
}

This maps the item codes, A01, A02, etc. to the respective sums of their quantities.


You can get the output, sorted by the code, with:

map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered((e) -> System.out.println(e.getKey() + " " + e.getValue()));

Note: Using .forEachOrdered(System.out::println) instead, produces output like A01=4, which is almost the same as the example you gave, and a little simpler than the above.



Related Topics



Leave a reply



Submit