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

Recommended Answers

All 5 Replies

i solved it with the following code


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));


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

     flatMap(x -> x.stream()).
     mapToDouble(x -> x.getAmount()).

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..

     flatMap(x -> x.stream()).
     mapToDouble(x -> x.getAmount()).

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, learning, and sharing knowledge.