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

Tranforming a Map containing Sets into a Map of Set-Sizes

This is my hash map:

HashMap<Customer, HashSet<Car>> carsBoughtByCustomers = ...

How can I get a new HashMap that will contain for each customer the amount of cars, i.e. the size of the HashSet?

I want to do this without loops, but using streams only.

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

My attempt:

HashMap<Customer, Integer> result = (HashMap<Customer, Integer>)
    carsBoughtByCustomers.entrySet().stream()
        .map(e -> e.getValue().size());

>Solution :

You need to apply a terminal operation in order to obtain a result from the stream, collect() in this case, which expects a Collector.

map() – is an intermediate operation, it produces another stream, i.e. it’s meant to transform the stream-pipeline but not to generate a result. Therefore, a stream-statement like this myMap.entrySet().stream().map() results to a Stream, and is not assignable to a variable of type Map.

Map<Customer,Integer> result = carsBoughtByCustomers.entrySet().stream()
            .collect(Collectors.toMap(
                Map.Entry::getKey,
                entry -> entry.getValue().size()
            ));

Sidenotes:

  • Writing code against interfaces like Map and Set, not concrete types like HashMap and HashSet, makes your code more flexible. See: What does it mean to "program to an interface"?
  • A stream without a terminal operation is perfectly valid, i.e. it would compile (if there are no errors is the code), but would not be executed.
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