I have got Car object with parameters like:
private String model;
private BigDecimal price;
private Color color;
private BigDecimal milleage;
private List<String> components;
I created list of Car objects:
var cars = List.of(
Car.create("FORD", BigDecimal.valueOf(120000), Color.RED, BigDecimal.valueOf(150000),
List.of("AIR CONDITIONING", "VOICE SERVICE")),
Car.create("FORD", BigDecimal.valueOf(160000), Color.RED, BigDecimal.valueOf(150000),
List.of("AIR CONDITIONING", "VOICE SERVICE")),
Car.create("AUDI", BigDecimal.valueOf(200000), Color.BLACK, BigDecimal.valueOf(195000),
List.of("NAVIGATION", "AUTOMATIC GEARBOX")),
Car.create("FIAT", BigDecimal.valueOf(70000), Color.BLUE, BigDecimal.valueOf(85000),
List.of("AIR CONDITIONING", "MANUAL GEARBOX")));
Now I want to create Map<String, List<Car>>
where the string is element of component list and List<Car>>
is list of Car
objects which contain this component.
I tried something like this based on some similar problems but really do not know how to solve this problem:
static Map<String, List<Car>> carsThatGotComponent(List<Car> cars) {
return cars.stream()
.flatMap(car -> car.getComponents()
.stream()
.map(component -> new AbstractMap.SimpleEntry<>(car, component)))
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Map.Entry::getValue)));
}