How to get sum of stipend of all students based on canteen id through Java 8 streams?

I have a class Student with 3 fields: name, canteenId, stipend

public class Student {
    String name;
    String canteenId;
    int stipend;
}

In the main class, I have

List<Student> l = new ArrayList<>();

Now here i want a map which have a canteenID as key and value as sum of stipend of all students working here?

I am able to do it thru prior java version 7 but unable to do it thru single line statement.

Thanks in advance.

2 answers

  • answered 2019-07-18 15:05 Deadpool

    By using java-8 use Collectors.groupingBy to group by based on canteenId and them sum all the students stipend using Collectors.summingInt

    Map<String, Integer> result = list
                       .stream()
                       .collect(Collectors.groupingBy(Student::getCanteenId,
                                Collectors.summingInt(Student::getStipend)));
    

  • answered 2019-07-18 15:05 Michael

    You can use collectors for this:

    Map<String, Integer> result = l.stream()
       .collect(Collectors.groupingBy(Student::getCanteenId, 
                Collectors.summingInt(Student::getStipend))
       )