Friday, November 9, 2018

Java 8 - Streams - sum()

Greetings!

Let's say we want to calculate total marks for a student for all subjects.


public class Subject {
    private String name;
    private Integer marks;
}


int totalMarks = subjects.stream().map(Subject::getMarks).sum();


This is not working because stream doesn't have sum() operation. That make sense because stream is generic and it doesn't have any meaning for total (sum) operation for an object.
And also if we use Integer, behind the scene it will covert to int (unboxing). For a large data set this will be a costly operation.
So, to get our desired result we to need to convert our stream into IntStream which offers the sum operation.


int totalMarks = subjects.stream().mapToInt(Subject::getMarks).sum();



  • mapToInt - this intermediate operation returns IntStream



No comments:

Post a Comment