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

Map of List: Sum all the values of the list class

I have this class

public Car(Colour colour, int passengers) {
    this.colour = colour;
    this.passengers = passengers;
}

Where Colour is an enum:

   public enum Colour {
    RED, YELLOW, GREEN, BLACK, WHITE, BLUE, GREY
}

I have created this map:

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

Map<Colour, List<Car>> colourListMap = new HashMap<>();

Imagine we populate the map of lists:

    Car yellowCar = new Car(Colour.YELLOW, 4);
    Car blueCar = new Car(Colour.BLUE, 1);
    Car blackCar = new Car(Colour.BLACK, 3);

    Map<Colour, List<Car>> map = carMemory.addCarByColour(yellowCar);
    carMemory.addCarByColour(blueCar);
    carMemory.addCarByColour(blackCar);

As well with 2 instances of the same colour:

    Car redCar = new Car(Colour.RED, 2);
    Car redCar2 = new Car(Colour.RED, 6);
    Map<Colour, List<Car>> map = carMemory.addCarByColour(redCar);
    carMemory.addCarByColour(redCar2);

Is there a simple way to sum all the passengers from the Car class? Instead to call the key by Colour? I was thinking to Java 8 Stream… but I m not very confident.

I know this isn’t correct.

int size =  map.values()
                .stream()
                .mapToInt(Collection::size)
                .sum();

>Solution :

If you need a sum of all the passengers for all cars in the map that will do the job:

            map.values()
                .stream()
                .flatMap(List::stream) // Stream of car objects
                .mapToInt(Car::getPassengers)
                .sum();

Side note:

  • instead of HashMap for a Map with enum-keys use EnumMap, this special-purpose implementation is designed to be used only with enums and has better performance.
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