Home > Net >  Map of List: Sum all the values of the list class
Map of List: Sum all the values of the list class

Time:02-10

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:

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

CodePudding user response:

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

Example for filtering colors:

           map.entrySet()
                .stream()
                .filter(entry -> entry.getKey() == Colour.RED ||
                                 entry.getKey() == Colour.BLACK) // only entries for BLACK and RED will remain
                .map(Map.Entry::getValue) // Stream<List<Car>>
                .flatMap(List::stream) // Stream<Car>
                .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.
  •  Tags:  
  • Related