我有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可能包含重复元素,如此处分别为start和end的1和2。如果列表中有重复的元素,我想只保留一个最大的count值并丢弃其他元素。
Start| End | Count
5 | 6 | 1
7 | 8 | 1
1 | 2 | 3
这是我期待的结果。怎么办呢?
答案 0 :(得分: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);
这是compareWith
类中的Counter
函数。
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 :(得分:-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);
}