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();
>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
HashMapfor a Map with enum-keys use EnumMap, this special-purpose implementation is designed to be used only with enums and has better performance.