JAVA list对象排序加去重问题
对象类实现继承Comparable接口重写compareTo方法实现排序功能,重写equals方法实现去重功能(根据ID去重)
public class TestAbilityAnalyze implements Comparable<TestAbilityAnalyze> {
private String abilityID;
/**
* 能力名称
*/
private String abilityName;
/**
* 个人正确率
*/
private double accuracy;
/**
* 班级正确率
*/
private double averageByClassID;
/**
* 年级正确率
*/
private double averageByGradeID;
public String getAbilityID() {
return abilityID;
}
public void setAbilityID(String abilityID) {
this.abilityID = abilityID;
}
public String getAbilityName() {
return abilityName;
}
public void setAbilityName(String abilityName) {
this.abilityName = abilityName;
}
public double getAccuracy() {
return accuracy;
}
public void setAccuracy(double accuracy) {
this.accuracy = accuracy;
}
public double getAverageByClassID() {
return averageByClassID;
}
public void setAverageByClassID(double averageByClassID) {
this.averageByClassID = averageByClassID;
}
public double getAverageByGradeID() {
return averageByGradeID;
}
public void setAverageByGradeID(double averageByGradeID) {
this.averageByGradeID = averageByGradeID;
}
@Override
public int compareTo(TestAbilityAnalyze o) {
// TODO Auto-generated method stub
return (int) (this.getAccuracy() - o.getAccuracy());
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Test))
return false;
TestAbilityAnalyze other = (TestAbilityAnalyze) obj;
if (abilityID == null) {
if (other.abilityID == null)
return true;
else
return false;
} else {
if (abilityID.equals(other.abilityID))
return true;
else
return false;
}
}
}
根据正确率排序,然后使用set去重
Collections.sort(analyzes);
Set<TestAbilityAnalyze> result = new TreeSet<>((o1, o2) -> o1.getAbilityID().compareTo(o2.getAbilityID()));
result.addAll(analyzes);