mcasdf
mcasdf

Reputation: 43

Count the elements in the values while groupingBy an attribute in key

I have a Map<Owner, List<Car>> as ownerMap. My Car class has the getColor() and getPrice() methods. My Owner class has the getCity() method.

I want to count the car's grouping by cities. (For example: Budapest: 4 (cars))

This is my code so far :

List<String> cities = ownerMap.entrySet()
                .stream()
                .map(m -> m.getKey().getCity())
                .distinct()
                .collect(Collectors.toList());

Upvotes: 1

Views: 352

Answers (1)

Mathieu Fortin
Mathieu Fortin

Reputation: 1048

You should take a look at Collectors.groupingBy and Collectors.summingInt.

For example, something like:

Map<String, Integer> cities=ownerMap.entrySet()
            .stream()
            .collect(Collectors.groupingBy(e -> e.getKey().getCity(), Collectors.summingInt(e -> e.getValue().size())));

cities.forEach((name, count) -> {
        System.out.println(name + ":" + count);
    });

From the Collectors.groupingBy documentation:

Returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

In your case, the classification function is by city (entry.getKey().getCity()) and your reduction operation is a sum of Cars list size by key (entry.getValue().size()).

EDITED Modified to get a sum of cars (list size) by city

Upvotes: 3

Related Questions