2017-05-19 54 views
-6

我有一個ArrayList。它的格式如下。如何僅保留ArrayList中具有最大值的對象?

List interval = new ArrayList<Counter>(); 

    public class Counter { 
     private int start; 
     private int end; 
     private int count; 
     ..... 
    } 


Start| End | Count 
1 | 2 | 2 
5 | 6 | 1 
1 | 2 | 2 
7 | 8 | 1 
1 | 2 | 3 

ArrayList中可能包含分別重複的元素也喜歡在這裏1和2的開始和結束。如果列表中有重複的元素,我只想保留count的最大值並丟棄其他元素。

Start| End | Count 
5 | 6 | 1 
7 | 8 | 1 
1 | 2 | 3 

這是我期待的結果。如何做呢 ?

+0

如果這些數據來自數據庫,那麼您應該絕對在這裏處理它。 –

+0

@TimBiegeleisen不,它不是來自數據庫。 – mjm

+0

與@ Turing85似乎暗示的是相反的,[沒有禁止作業問題](https://meta.stackoverflow.com/questions/334822/how-do-i-ask-and-answer-homework-questions )。但是,如果這是一個標籤,那麼這樣做很有幫助。而且你應該顯示你已經嘗試過的東西,並且你應該期待提示,而不是完整的答案。 –

回答

0

這應該是工作。

List<Counter> toRemove = new ArrayList<Counter>(); 

Collections.sort(interval, (first, second) -> { 

     int c = 0; 

     if (first.compareWith(second)) { 
      if (first.getCount() <= second.getCount()()) 
       toRemove.add(first); 
      else if (first.getCount() >= second.getCount()) 
       toRemove.add(second); 
     } else 
      c = first.getCount().compareTo(second.getCount()); 

     return c; 
    } 
); 

interval.removeAll(toRemove); 

這是Counter類中的compareWith函數。

public boolean compareWith(Counter second) { 

    if (this.getStart().equals(second.getStart()) 
      && this.getEnd().equals(second.getEnd()) 
      && this.getStart().equals(second.getEnd())) { 
     return true; 
    } 

    return false; 
} 
-1

嘗試循環訪問ArrayList並檢查重複的內容。

ArrayList<Counter> interval = new ArrayList<Counter>(); 
    ArrayList<Counter> interval2 = new ArrayList<Counter>(); 

     for (int i = 0; i < interval.size(); i++) { 

      Counter counteri = interval.get(i); 
      int c = 1; 
      for (int j = i; j < interval.size()-1; j++) { 

       Counter counterj = interval.get(j); 
       int diffStart = counteri.start - counterj.start; 
       int diffEnd = counteri.end - counterj.end; 

       if(diffStart == 0 && diffEnd == 0){ 

        c++; 
       } 
      } 
      counteri.setCount(c); 
      interval2.add(counteri); 
     } 
相關問題