Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to multiply key * value in Map in Java?

I have this class:

class Product {
    public double price;

    public Product(double price) {
        this.price = price;
    }
}

And a Map:

Map<Product, Integer> products = new HashMap<>();

That contains several products added like so:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

products.put(new Product(2.99), 2);
products.put(new Product(1.99), 4);

And I want to calculate the sum of all products multiple the values using streams? I tried:

double total = products.entrySet().stream().mapToDouble((k, v) -> k.getKey().price * v.getValue()).sum();

But doesn’t work. Thanks

I expect:

(2.99 * 2) + (1.99 * 4) = 5.98 + 7.96 = 13.94

>Solution :

The stream of entries needs single parameter lambda for each entry, not (k,v):

double total = products.entrySet().stream().mapToDouble(e -> e.getKey().price * e.getValue()).sum();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading