Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collectors.summingLong or mapToLong to summarize long values

Tags:

java

java-8

I've got a list of objects with a value and want to summarise all these values. What is the preferred way to do this in Java 8?

public static void main(String[] args) {
    List<AnObject> longs = new ArrayList<AnObject>();
    longs.add(new AnObject());
    longs.add(new AnObject());
    longs.add(new AnObject());

    long mappedSum = longs.stream().mapToLong(AnObject::getVal).sum();
    long collectedSum = longs.stream().collect(Collectors.summingLong(AnObject::getVal));

    System.out.println(mappedSum);
    System.out.println(collectedSum);
}

private static class AnObject {
    private long val = 10;

    public long getVal() {
        return val;
    }
}

I think mapToLong is more straight forward but I can't really motivate why.

Edit: I've updated the question by changing from summarizeLong to summingLong, that's why some answers and comments might seem a bit off.

like image 762
softarn Avatar asked Oct 27 '25 22:10

softarn


1 Answers

I think using Collectors.summarizingLong(AnObject::getVal)) would do more work than you need it to do, as it computes other statistics beside the sum (average, count, min, max, ...).

If you just need the sum, use the simpler and more efficient method :

long mappedSum = longs.stream().mapToLong(AnObject::getVal).sum();

After you changed Collectors.summarizingLong to Collectors.summingLong, it's hard to say which option would be more efficient. The first option has an extra step (mapToLong), but I'm not sure how much difference that would make, since the second option does more work in collect compared to what the first option does in sum.

like image 145
Eran Avatar answered Oct 29 '25 11:10

Eran