我将List Object转换为Map String,List Object时遇到问题。我正在寻找具有汽车中所有组件的键名称的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;
}
答案 0 :(得分:2)
您也可以使用流来做到这一点,但是我发现它更具可读性:
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())
));
}
答案 1 :(得分:0)
我知道这是一个Java问题,并且已经有一个Java答案。但是,我想补充一点,Kotlin是一种JVM语言,可以与Java完美地互操作,您可以非常轻松,干净地执行以下操作:
val carsByComponent = cars
.flatMap { it.components }
.distinct()
.map { component -> component to cars.filter { car -> component in car.components } }
.toMap()
或更简洁,但可读性更差:
val carsByComponent = cars
.flatMap { car -> car.components.map { it to car } }
.groupBy { it.first }
.mapValues {it.value.map { it.second }}