[英]Java TreeSet Comparator
我有一個包含以下字段的Vehicle類:baseVehicleId,subModelId,notes和partNo
如果是相同的baseVehicleId,subModelId和partNo,我希望保留最長注釋的對象(並刪除其他注釋)
我有這個:
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);
我如何修改此代碼:/? 因此,例如,如果我所有字段均相等且注釋的長度較大,則刪除其他對象。
比較器的工作只是說兩個對象中的哪個先出現-在比較過程中沒有機制可以操縱基礎集合。 我認為您可能會以一種稍微不同的方式來考慮:在將對象添加到集合之前執行過濾邏輯。
為了簡單起見,我建議僅使用標准列表,例如ArrayList
。 另外,您還需要重寫Vehicle類中的equals()
方法,如果兩個Vehicle共享相同的ID和部件號,則該方法返回true
。
在添加新車輛時,您可以執行以下操作:
int vehicleIndex = myvehicles.indexOf(vehicle) // -1 if missing, otherwise 0 or greater to represent the index position
if (vehicleIndex == -1) {
// No item in the list shares the ids/model/part numbers so can add
myvehicles.add(vehicle)
} else {
// There's another similar vehicle, better compare their notes:
Vehicle existingVehicle = myvehicles.get(vehicleIndex); // retrieve the object from list so that we can compare it
// check if the new vehicle has longer notes
if (vehicle.getOurNotes().length > existingVehicle.getOurNotes().length) {
// if it does, remove the old one from the list
myvehicles.remove(vehicleIndex);
// and add the new one. Effectively we've done a replacement
myvehicles.add(vehicle)
}
}
顯然,它不會自動排序,但是您可以通過運行還接受Comparator的Collections.sort()方法添加一批商品之后執行此操作,但這一次您的比較器現在可以專注於詳細說明排序的特定任務,因為您知道該列表已預先過濾,因此您不必擔心要過濾掉項目。
只需遍歷集合,並使用它刪除所有不符合您要求的it.remove()
。
您可能還需要查看Java 8集合功能,該功能將允許您執行諸如過濾集合之類的事情,因為這也將滿足您的需求。
我認為你應該使用該方法
maximum = Collections.max(collection, comparator);
用於搜索最多的元素,然后刪除其他帶有
collection.remove();
在比較器內部,您不能從集合中刪除。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.