If I had: ArrayList
with the double values inside, how should I do to add up all the ArrayList elements?
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
Using Java 8 streams:
double sum = m.stream()
.mapToDouble(a -> a)
.sum();
System.out.println(sum);
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;
}
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;
}
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;