Home > Back-end >  Java remove duplicate Object properties
Java remove duplicate Object properties

Time:11-05

I'm trying to return a List with no duplicate properties (using CSVRecord).

I received a CSV like this one:

brand;color
bmw;red
bmw;blue
jaguar;yellow
jaguar;red
mercedes;bleu
fiat;green

I've a method like this (just for example):

public List<Car> convert(List<CSVRecord> csvRecordList) {
    Map<Car, List<CSVRecord>> csvRecordsByCar = csvRecordList.stream()
        .collect(Collectors.groupingBy(csvRecord -> Car.builder()
            .brand(csvRecord.get("brand"))
            .color(Collections.singletonList(csvRecord.get("color")))
            .build()
        ));

    return csvRecordsByCar .entrySet().stream()
        .map((Map.Entry<Car, List<CSVRecord>> csvRecordByCar) ->
            Car.builder()
                .brand(csvRecordByCar.getKey().getBrand())
                .color(csvRecordByCar.getKey().getColor())
                .build()
        )
        .collect(Collectors.toList());
}

For now it's returning me a Car list object with duplicates brand. what i'd like is not to have duplicate brand and merge brand's color in a list, like:

Car{
  brand: "bmw",
  color: ["red", "blue"]
}

I'm pretty new in java and its a technical probleme to me, thx you for help :)

CodePudding user response:

Without seeing the car class, I'd assume from the first part of the function is that you are groupingBy Car which relies on you implementing equals and hashcode.

So that is probably why you are getting duplicates like

Car{
  brand: "bmw",
  color: ["red"]
}

Car{
  brand: "bmw",
  color: ["blue"]
}

The another option to consider is groupBy brand name and collect a list of colors then map that result into your List of Car.

CodePudding user response:

Assuming your car class has colors as list making the class look like below:

public class Attribute {
private String name;
private List<String> color;
}

You need to add the following method in your car class,

public void addColor(String color){
    if(null==this.color){
        this.color = new ArrayList<>();
        this.color.add(color);
    } else {
        this.color.add(color);
    }
}

and try this:

    public List<Car> convert(List<CSVRecord> csvRecordList) {
Map<String, List<CSVRecord>> csvRecordsByCar = csvRecordList.stream()
    .collect(Collectors.groupingBy(csvRecord -> csvRecord.get("brand")));

List<Attribute> result= new ArrayList<>();
    for (Map.Entry mapElement : csvRecordsByCar.entrySet()) {
        String key = (String)mapElement.getKey();
        List<CSVRecord> value = (List<CSVRecord>) mapElement.getValue();
        Car car=new Car();
        car.setName(key);
        for (CSVRecord csvRecord2 : value) {
            car.addColor(csvRecord2.get("color"));
        }
        result.add(car);
    }
     return result;
    }
  • Related