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 int
s.
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()));
}
}
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
How to Mix --Class-Path and --Module-Path in Javac (Jdk 9)
Using Ntlm Authentication in Java Applications
Is There a Sophisticated File System Monitor for Java Which Is Freeware or Open Source
Jackson Change JSONignore Dynamically
How to Change the Color of Specific Words in a Jtextpane
Weird Java Behavior with Casts to Primitive Types
Suppress Deprecated Import Warning in Java
Java: How to Split a String by a Number of Characters
Spark Spark-Submit --Jars Arguments Wants Comma List, How to Declare a Directory of Jars
How Does System.Out.Print() Work
Getting Class Cast Exception Where Both Classes Are Exactly the Same
How to Insert a Row Between Two Rows in an Existing Excel with Hssf (Apache Poi)
Can Someone Please Explain Me @Mapsid in Hibernate
Java Native Method Source Code
JSON Parameter in Spring MVC Controller
Why Aren't Integers Cached in Java