I have a Vehicle class with fields: baseVehicleId, subModelId, notes and partNo
If is the same baseVehicleId, subModelId and partNo , i want the object with the longest notes to remain( and delete the others)
I have this:
Comparator<Vehicle> comparator = new Comparator<Vehicle>() {
@Override
public int compare(Vehicle a, Vehicle b) {
if(a.baseVehicleId().equals(b.baseVehicleId()) && String.valueOf(a.subModelId ()).equals(String.valueOf(b.subModelId ()))
&& String.valueOf(a.partNo ()).equals(String.valueOf(b.partNo ()))
))
return a.getOurnotes().compareTo(b.getOurnotes());
// not good I know
return 1;
}
};
TreeSet<Vehicle> treeSet = new TreeSet<Vehicle>(comparator);
How can i modify this code :/? So for example if i have all the fields equal and the length of notes are greater then delete the other objects.
I think you should use the method
maximum = Collections.max(collection, comparator);
for searching the maximum of the elements and then just delete the others with
collection.remove();
Inside the comparator you can't delete from the collection.