Hey everyone, I have the following list in my code

public class order {
    private float amount;

    public float getAmount() {
        return this.amount;
    }
}

and in main function I have the following list

List<List<Order>> ordersList

I want to iterate the list through Streams in java 8 in order to calculate the total amount of all the orders. How do I do that? Please help

i solved it with the following code

ordersList.stream().map(x->x.getOrdersList())
                .collect(Collectors.toList())
                .stream()
                .flatMap(l->l.stream()).mapToDouble(z->z.getAmount()).sum();

Welcome to Java 8!

That code seems to have acumulated some extra code, presumably from trial-and-error.

I took your code, added a litte constructor to Order, and set up some test data like this

        List<List<Order>> list = new ArrayList<>();

        List<Order> list1 = new ArrayList<>();
        List<Order> list2 = new ArrayList<>();

        list1.add(new Order(1));
        list2.add(new Order(2));
        list2.add(new Order(3));

        list.add(list1);
        list.add(list2);

now all it needs to sum all the amounts is to flatten the nested lists, convert the Orders to amounts, and sum them...

list.stream().
     flatMap(x -> x.stream()).
     mapToDouble(x -> x.getAmount()).
     sum();

hey thanks :D

but the streams seem to be slower than the foreach loops

That's quite likely. You are replacing low-level procedural code (loops etc) with higher-level declarative code. However, I think you would have to be processing a lot of data for any difference to be significant.
It gets a lot more interesting if you add one word..

list.parallelStream().
     flatMap(x -> x.stream()).
     mapToDouble(x -> x.getAmount()).
     sum();

now Java will use multiple threads to process parts of the data in parallel. Assuming you have multi-cpu hardware this can give you very significant gains, and the code is orders of magnitude easier than splitting it up and running loops in multiple threads yourself.

thanks :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.