【问题标题】:How to keep only the object with the maximum value in the ArrayList?如何只保留ArrayList中具有最大值的对象?
【发布时间】:2017-10-19 18:38:34
【问题描述】:

我有一个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 分别用于开始和结束。如果列表中有重复的元素,我想只保留一个最大值并丢弃其他元素。

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

这是我所期待的结果。怎么办?

【问题讨论】:

  • 如果这些数据来自数据库,那么您绝对应该在那里处理它。
  • @TimBiegeleisen 不,它不是来自数据库。
  • 与@Turing85 似乎暗示的相反,there is no ban on homework questions。但是,如果这是一个,那么将其标记为这样会很有帮助。你绝对应该展示你尝试过的东西,你应该期待得到提示,而不是完整的答案。
  • @Choirbean 我没有暗示任何事情,尤其是没有禁止家庭作业问题。否则我会投票结束这个问题。
  • @Choirbean:虽然允许家庭作业问题,但没有显示尝试,没有使用此尝试,问题仍然过于宽泛,因此可以提出有效的论据来关闭它。同样根据元讨论,通常希望家庭作业海报展示他们的努力成果。

标签: java arraylist collections


【解决方案1】:

这应该可以工作。

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;
}

【讨论】:

    【解决方案2】:

    尝试遍历您的 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);
            }
    

    【讨论】:

      猜你喜欢
      • 2017-12-31
      • 2021-07-19
      • 2017-12-27
      • 2020-06-14
      • 2015-11-17
      • 2015-06-23
      • 2017-10-12
      • 2017-06-18
      • 2012-09-30
      相关资源
      最近更新 更多