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()));
}
}
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
Remove Duplicates from a List of Objects Based on Property in Java 8
Write to Text File from Multiple Threads
Java Stream Collectors.Groupingby() Multiple Fields
How to Do a Limit Query in Jpql or Hql
Javax.Validation - Allow Null But Validate If the Value Is Not
How to View Apache Parquet File in Windows
How to Subtract a Constant Value from All Elements of an Array
How to Pass External Jar File to Spring Boot Project
How to Run Multiple Jobs in Spring Batch Using Annotations
How to Run Java Program in Terminal With External Library Jar
Java How to Retrieve More Than 1 Million Rows in a Resultset
Java Regex to Validate Full Name Allow Only Spaces and Letters
Fixing Apache V9.0 Server Tomcat V9.0 Server At Localhost Failed to Start Error
Field Required a Bean Which Could Not Be Found in Springboot
Junit 5 - No Parameterresolver Registered for Parameter
How to Query Multiple Hash Keys in Dynamodb