使用流的对象字段列表的总和

时间:2017-07-21 14:48:34

标签: java java-8 java-stream

我有一个对象

Class DummyObject() {
    double first;
    double second;
    double third;
    double fourth;
}

Class SomeObject() {
    List<DummyObject> objectList;
}

Class HighestObject() {
    List<SomeObject> objectList;
}

给出了SomeObject类型的变量。我必须找出DummyObject中四个字段的总和是否等于数量X.

使用for循环,它可以很容易地写成:

for(SomeObject someObject : hightestObject.getObjectList()) {
    for(DummyObject dummyObject : someObject.getObjectList()){
        if((dummyObject.first + dummyObject.second + dummyObject.third + dummyObject.fourth) != X) {
             return false;
        }
    }
}

我们怎样才能使用java流?

2 个答案:

答案 0 :(得分:2)

您可以合并flatMapanyMatch

HighestObject h = ...;

boolean foundNotX = h.getObjectList().stream() //Stream<SomeObject>
                  .flatMap(so -> so.getObjectList().stream()) //Stream<DummyObject>
                  .mapToDouble(o -> o.first + o.second + o.third + o.fourth) //DoubleStream
                  .anyMatch(sum -> sum != X);
if (foundNotX) return false;

根据您的目标,使用.allMatch(sum -> sum == X)可能更合适。

答案 1 :(得分:2)

试试这个。

return hightestObject.getObjectList().stream()
    .flatMap(someObject -> someObject.getObjectList().stream())
    .allMatch(dummyObject ->
        dummyObject.first + dummyObject.second + dummyObject.third + dummyObject.fourth == X);