Java 8 stream groupingBy object field with object as a key

user3529850 :

I have the following structure of classes (given example is meaningless, I've made it just for the question purposes):

public class ManufacturerDto {
    private String name;
    private Boolean withConfirmation;

    //getters and setters omitted for brevity
}

public class CarDto {

    private ManufacturerDto manufacturer;

    //getters and setters omitted for brevity
}

public abstract class VehicleDto {

    private list<CarDto> cars = new ArrayList<>();

    //getters and setters omitted for brevity
}

public class EuropeanMarketCarDto extends VehicleDto {

    public Map<String, List<CarDto>> getCarManufacturerToCarsMap() {

       return this.getCarDtos()
                .stream()
                .collect(Collectors.groupingBy(e -> e.manufacturer().getName()));

        //getters and setters omitted for brevity
    }
}

In the given scenario, groupingBy returns pretty much everything I want, but I have a problem with the key. In getCarManufacturerToCarsMap() method I would like to have a manufacturer object as a key but I am not even sure if that is possible using groupingBy. What can I do, to return a map of Map<Manufacturer, List<CarDto>> ?

Ousmane D. :

If you actually want to avoid having the map key as a String i.e. Map<String, List<CarDto>> and instead have a Map<Manufacturer, List<CarDto>> you can group by as follows:

this.getCarDtos()
      .stream()
      .collect(Collectors.groupingBy(e -> e.getManufacturer()));

Note that this would require you to override equals and hashcode method in your Manufacturer class defining that two given objects are equal if they have the same name.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=76702&siteId=1