首页 > 解决方案 > Group list by elements of nested list

问题描述

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

标签: javadictionaryjava-streamgrouping

解决方案


Collectors#mapping需要作为第二个参数的下游Collector,而不是映射函数。

public static <T,U,A,R> Collector<T,?,R> mapping(
    Function<? super T,? extends U> mapper, 
    Collector<? super U,A,R> downstream)

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

只要您使用或更高版本,您就可以使用Collectors#flatMapping将整个 Stream 简化为一个收集器:

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

推荐阅读