Grupuj listę według elementów listy zagnieżdżonej [duplikat]
 Jan 25 2021
Mam obiekt Car o parametrach takich jak:
private String model;
private BigDecimal price;
private Color color;
private BigDecimal milleage;
private List<String> components;
 
    Stworzyłem listę obiektów samochodów:
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")));
 
    Teraz chcę utworzyć miejsce, w Map<String, List<Car>>którym ciąg jest elementem listy składników i List<Car>>jest listą Carobiektów, które zawierają ten składnik.
Próbowałem czegoś takiego w oparciu o kilka podobnych problemów, ale tak naprawdę nie wiem, jak rozwiązać ten 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)));
}
Odpowiedzi
2  NikolasCharalambidis Jan 25 2021 at 19:15
Collectors#mappingwymaga jako drugiego parametru podrzędnej funkcji Collector, a nie funkcji odwzorowującej.
public static <T,U,A,R> Collector<T,?,R> mapping( Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
Zamiast tego chcesz użyć Collectors.toList():
return cars.stream()
    .flatMap(car -> car.getComponents()
                       .stream()
                       .map(component -> new AbstractMap.SimpleEntry<>(car, component)))
    .collect(Collectors.groupingBy(
            AbstractMap.SimpleEntry::getValue,
            Collectors.mapping(AbstractMap.SimpleEntry::getKey, Collectors.toList())));
 
     Tak długo, jak użyć java-10 lub później, można użyć uprościć cały strumień do jednego kolektora używając Collectors#flatMappingjak z java-9 :
return cars.stream()
    .collect(Collectors.flatMapping(
             car -> car.getComponents()
                       .stream()
                       .map(component -> new AbstractMap.SimpleEntry<>(car, component)),
             Collectors.groupingBy(AbstractMap.SimpleEntry::getValue,
                     Collectors.mapping(AbstractMap.SimpleEntry::getKey, 
                             Collectors.toList()))));