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

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...