Sum all the elements java arraylist

后端 未结 5 834
醉话见心
醉话见心 2020-11-27 05:21

If I had: ArrayList m = new ArrayList(); with the double values ​​inside, how should I do to add up all the ArrayList elements?

相关标签:
5条回答
  • 2020-11-27 05:58

    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

    0 讨论(0)
  • 2020-11-27 05:59

    Using Java 8 streams:

    double sum = m.stream()
        .mapToDouble(a -> a)
        .sum();
    
    System.out.println(sum); 
    
    0 讨论(0)
  • 2020-11-27 06:05

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 06:12

    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;
    }
    
    0 讨论(0)
  • 2020-11-27 06:23

    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;
    
    0 讨论(0)
提交回复
热议问题