Java 8列表到地图的转换

提问

我将列表对象转换为映射字符串,列表对象时遇到问题.我正在寻找具有汽车中所有组件的键名称的Map,并且值由具有该组件的汽车表示

public class Car {
    private String model;
    private List<String> components;
    // getters and setters
}

我写了一个解决方案,但正在寻找更好的流解决方案.

public Map<String, List<Car>> componentsInCar() {
    HashSet<String> components = new HashSet<>();
    cars.stream().forEach(x -> x.getComponents().stream().forEachOrdered(components::add));
    Map<String, List<Car>> mapCarsComponents  = new HashMap<>();
    for (String keys : components) {
        mapCarsComponents.put(keys,
                cars.stream().filter(c -> c.getComponents().contains(keys)).collect(Collectors.toList()));
    }
    return mapCarsComponents;
}

最佳答案

您也可以使用流来做到这一点,但是我发现这更具可读性:

public static Map<String, List<Car>> componentsInCar(List<Car> cars) {
    Map<String, List<Car>> result = new HashMap<>();
    cars.forEach(car -> {
        car.getComponents().forEach(comp -> {
            result.computeIfAbsent(comp, ignoreMe -> new ArrayList<>()).add(car);
        });
    });

    return result;
}

或使用流:

public static Map<String, List<Car>> componentsInCar(List<Car> cars) {
    return cars.stream()
               .flatMap(car -> car.getComponents().stream().distinct().map(comp -> new SimpleEntry<>(comp, car)))
               .collect(Collectors.groupingBy(
                   Entry::getKey,
                   Collectors.mapping(Entry::getValue, Collectors.toList())
               ));
}