Search code examples
javafunctional-programmingjava-8reductioncollectors

Reducing integer attributes in a list of objects


I have a model of this structure

public class MyModel {
        private long firstCount;
        private long secondCount;
        private long thirdCount;
        private long fourthCount;

        public MyModel(firstCount,secondCount,thirdCount,fourthCount) 
        {
        }
        //Getters and setters

}  

Assume that I have a list of these models with the following data

MyModel myModel1 = new MyModel(10,20,30,40);
MyModel myModel2 = new MyModel(50,60,70,80);

List<MyModel> modelList = Arrays.asList(myModel1, myModel2);

Supposing I want to find out the sum of firstCount in all the models, I could do this

Long collect = modelList.stream().collect
(Collectors.summingLong(MyModel::getFirstCount));

What if I want to find out sum of attributes in all the models in one pass ?Is there any way to achieve this ?

the output should be something like

  • sum of firstCount = 60
  • sum of secondCount = 80
  • sum of thirdCount = 100
  • sum of fourthCount = 120

Solution

  • Using MyModel as accumulator:

    MyModel reduced = modelList.stream().reduce(new MyModel(0, 0, 0, 0), (a, b) ->
                          new MyModel(a.getFirstCount() + b.getFirstCount(),
                                      a.getSecondCount() + b.getSecondCount(),
                                      a.getThirdCount() + b.getThirdCount(),
                                      a.getFourthCount() + b.getFourthCount()));
    System.out.println(reduced.getFirstCount());
    System.out.println(reduced.getSecondCount());
    System.out.println(reduced.getThirdCount());
    System.out.println(reduced.getFourthCount());