Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 List to Map conversion

I have a problem with conversion List Object to Map String, List Object. I'm looking for Map with a keys name of all components in cars, and a value is represented by cars with this component

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

I write a solution but looking for a better stream solution.

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;
}
like image 755
user11042713 Avatar asked Jan 25 '26 03:01

user11042713


1 Answers

You could do it with streams too, but I find this a bit more readable:

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

Or using stream:

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())
               ));
}
like image 93
Eugene Avatar answered Jan 26 '26 18:01

Eugene