Summing up several different fields in a list of objects using api streams?

In Java 8, if I have a list of objects like this:

MyObject double a; double b; double c; 

I want to get the results of each of these fields in the list of objects. One way to do this:

 double totalA = myListOfObjects.stream().map(e -> e.getA()).reduce(0.0, (x, y) -> x + y); double totalB = myListOfObjects.stream().map(e -> e.getB()).reduce(0.0, (x, y) -> x + y); double totalC = myListOfObjects.stream().map(e -> e.getC()).reduce(0.0, (x, y) -> x + y); 

But is there any way to combine this in one pass through a list of objects that use api threads? If I just wrote a for / while loop (see below) and manually added 3 total values โ€‹โ€‹that would look more efficient than the above 3 lines of code)

 for (MyObject obj: myListOfObjects) { totalA += obj.getA(); totalB += obj.getB(); totalC += obj.getC(); } 

thanks

+6
source share
1 answer

You can reduce the number of new MyObject objects as follows:

 MyObject totals = myListOfObjects.stream() .reduce((x, y) -> new MyObject( x.getA() + y.getA(), x.getB() + y.getB(), x.getC() + y.getC() )) .orElse(new MyObject(0, 0, 0)); totalA = totals.getA(); totalB = totals.getB(); totalC = totals.getC(); 

Anyway, I donโ€™t think you should worry about performance here. All three solutions (2 in your question + mine above) have O(n) time complexity. I would recommend reading a little about premature optimization. Just go to the code that is most readable and easy to understand.

You can also extract code to sum two objects into a method of the MyObject class:

 public class MyObject { // fields, constructors, getters etc. public MyObject sum(MyObject other) { return new MyObject( this.a + other.a, this.b + other.b, this.c + other.c ); } } 

This will allow you to use the method reference: .reduce(MyObject::sum)

+9
source

Source: https://habr.com/ru/post/1258200/


All Articles