0
点赞
收藏
分享

微信扫一扫

List列表使用HashSet实现数据去重小技巧

在数据库中,可以使用distinct来去重,不过加上distinct会影响一定的性能,所以在一些特殊情况,数据量不是很大的情况,可以利用java集合Set的特性,Set集合数据是不重复的来进行数据过滤

实例代码:进行数据过滤,不过因为HashSet数据是无序的,所以数据是不排序的

public <T> List<T> distinctListBySet(List<T> list) {
return new ArrayList<T>(new HashSet<T>(list));
}

上面代码进行了无序排序,下面这个代码进行有序去查:

public <T> List<T> distinctListBySetOrder(List<T> originList) {
List<T> newList = new ArrayList<T>();
Set<T> sortSet = new HashSet<T>();
for (T entity: originList) {
if (sortSet.add(entity)) {
newList.add(entity);
}
}
return newList;
}


举报

相关推荐

0 条评论