'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:
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();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
