java 利用HashSet去重并保持排序
@(技能提升)[Java, 排序,ArrayList,HashSet]
1.去重
在java中 对arrayList 去重, 最便利的方式即利用HashSet的不可重复特性,直接去重:
List<Result> resultList = new ArrayList<>(new HashSet<>(resultList));
resultList 对象中的重复数据即可去出.
注意点:
1.需要根据实际需求定义 什么样的对象为 重复对象
, 在对象中重写 equals()
方法,
(备注:同时也要重写hashCode()
关于equals和hashCode之间的关系 可以参考: CSDN博客:Java中hashCode的作用):
例如:以下代码 重复的定义为: 两个对象id的相等,即为重复对象,如果不重写该方式,默认的重复定义为:两个对象完全相等,才是重复对象.
@Override
public boolean equals(Object another) {
if (this == another) {
return true;
}
if (another == null) {
return false;
}
if (getClass() != another.getClass()) {
return false;
}
Result ds = (Result) another;
if (this.id== null && ds.id!= null) {
return false;
}
if (!this.id.equals(ds.id)) {
return false;
}
return true;
}
@Override
public int hashCode() {
return this.id;
}
2.保持排序
在第一点中,可以取出重复数据,但是无法保证返回数据在原数组中的排序.
解决方案:
在Result
对象中添加额外用于排序的字段 tempId
,(或者新建对象TempResult
继承Result
,并在TempResult 中 添加tempId 属性).
public class Result {
/** 临时排序用字段*/
int tempId;
/** 其他字段*/
...
...
/** getter & setter */
...
...
}
去重之前,对集合List<Result> resultList
; 做以下处理:
int index=0;
//获取集合
List<Result> resultList=...;
//添加临时字段
for(Result result:resultList){
result.setTempId(index++);
}
//去重
resultList= new ArrayList<>(new HashSet<>(resultList));
//恢复排序
Result[] temp = new Result[resultList.size()];
resultList.toArray(temp);
//去重后恢复排序
Arrays.sort(temp, new Comparator<Result>() {
@Override
public int compare(Result result1, Result result2) {
return result1.getTempId() - result2.getTempId();
}
});
resultList=Arrays.asList(temp);
这样处理完毕就即可即去除重复,又保持顺序.