[英]How remove duplicates from list based on several conditions in Java
我有一個飛行對象列表,該對象具有id(Long)和destinations(String)。 我需要做的是刪除相同ID的重復條目。 但條件是要刪除這些元素,我只能保留目標列表最長的元素。
Flight{
Long id;
String destination;
}
列表排期<-這是必須根據條件進行過濾的內容。
列表示例:
flight1 -> id:456 , destination LON/DXB
flight2 -> id:456 , destination LON/DXB/IND
flight3 -> id:465 , destination LON/DXB/IND/CMB
flight4 -> id:555 , destination LON/DXB
flight5 -> id:666 , destination DXB/SHJ
flight6 -> id:666 , destination DXB/SHJ/BOM
根據給定的條件,我只能保留在列表中: flight3,flight4,flight6 。 其他航班不能在列表中。 我該怎么做?
您可以做的是創建一個映射,使關系在ID和實例之間傳遞。
在遍歷列表時,您檢查映射中是否存在具有相同ID的實例。 如果不是這種情況,則只需添加映射,否則就比較目標的長度(或要比較的任何內容),並在必要時更新映射。
Map<Long, Flight> map = new HashMap<>();
for(Flight f : flights) {
if(map.containsKey(f.id)) {
if(map.get(f.id).destination.length() < f.destination.length()) {
map.put(f.id, f);
}
} else {
map.put(f.id, f);
}
}
//you can even store them in a set
List<Flight> longestDestinationFlights = new ArrayList<>(map.values());
好的,我希望您有一個航班清單,例如: List<Flight>
。 我進一步假設,將有更多重復的條目,並且應存儲“更長”的目的地。
您要做的是使用迭代器進行迭代。 (刪除時不能使用for循環)
List<Flight> a = new ArrayList<>();
List<Flight> copy = new ArrayList<>();
Collections.copy(copy, a);
Iterator<Flight> it = a.iterator();
while(it.hasNext()){
Flight f = it.next();
if(shouldGetRemoved(f, copy)){
it.remove();
}
}
shouldGetRemoved
是您比較目的地的邏輯。 將是另一個遍歷副本的循環。
我的實現有點長,但是很容易。
這里的工作代碼。
這是代碼。
private static List<Flight> removeDuplicates(List<Flight> list) {
//sort the list, descending order of size of destination list
Collections.sort(list, new Comparator<Flight>() {
@Override
public int compare(Flight o1, Flight o2) {
if (o1.getId().equals(o2.getId())) {
int l1 = o1.getDestination().split("/").length;
int l2 = o2.getDestination().split("/").length;
if (l1 < l2) { //check whose destination list is long
return 1;
} else {
return -1;
}
}
return 0;
}
});
// remove duplicates
Set<Long> ids = new HashSet<>();
List<Flight> newList = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (!ids.contains(list.get(i).getId())) {
newList.add(list.get(i));
ids.add(list.get(i).getId());
}
}
return newList;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.