的流中的每個字段我要創建的對象的MyObject的實例,其中的每個將是薩姆在對象
該字段的值的總和字段創建對象
public class MyObject{
int value;
double length;
float temperature;
MyObject(int value, double length, float temperature){
this.value = value;
this.length = length
this.temperature = temperature
}
}
然後我構造對象列表:
List<MyObject> list = new ArrayList<MyObject>{{
add(new MyObject(1, 1d, 1.0f));
add(new MyObject(2, 2d, 2.0f));
add(new MyObject(3, 3d, 3.0f));
}}
我想創建對象(new MyObject(6, 6d, 6f)
)
這是很容易總結一個字段每流:
Integer totalValue = myObjects.parallelStream().mapToInt(myObject -> myObject.getValue()).sum(); //returns 6;
或
Double totalLength = myObjects.parallelStream().mapToDouble(MyObject::getLength).sum(); //returns 6d
,然後構造對象new MyObject(totalValue, totalLength, totalTemperature);
但我可以總結各個領域中的一個流? 我要流回到
new MyObject(6, 6d, 6.0f)
這可以避免創建中間的'MyObject'實例,與'reduce'的版本進行比較。 – frenzykryger