简体   繁体   中英

How can i loop trough nested objects and validate some calculations with lambda and streams

I need to loop trough nested objects validating some calculations. ex:

Category obj1 = new Category(0, 0, 10, null);
Category obj2 = new Category(2, 3, 6, obj1);
Category obj3 = new Category(2, 2, 4, obj1);

And i need to check if a parent exists following : sum2(qty * price = total) sum3(qty * price = total) and sum2+sum3== parent total

ex: (2*2==4) (3*3==6) and 4+6 == 10

How can i do that with lambda and streams?

public class Category {

    private int qty;
    private int price;

    private int total;

    private Category rootCategory;

}

Use Stream.of to create Category stream and then filter objects with rootCategory is not null

int sum = Stream.of(obj1, obj2, obj3)
        .filter(o -> Objects.nonNull(o.getRootCategory()))
        .mapToInt(c -> c.getQty() * c.getPrice())
        .sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM