List根据指定属性去重
一、根据指定条件去重
- 测试类
class Test{
private String name;
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
根据流的Collectors.collectingAndThen去除重复
/**
*一个属性去重
*/
// 其中 allList 是Test类的一个集合
List<Test> distinctList = allList
.stream()
.collect
(Collectors.collectingAndThen(Collectors.toCollection(
//根据age去重
() -> new TreeSet<>(Comparator.comparing(Test::getAge)))
, ArrayList::new));
/**
* 多个属性去重
* 其实就是将读个属性拼接当成比较条件
*/
// 其中 allList 是Test类的一个集合
List<Test> distinctList = allList
.stream()
.collect
(Collectors.collectingAndThen(Collectors.toCollection(
//根据age和name 两个属性去重
() -> new TreeSet<>(Comparator.comparing(
o -> o.getAge() + "-" + o.getName()
)))
, ArrayList::new));
如果存在重复的,则最后保留的是原始list 中索引最前的那一个(也就是第一个)
如果新的List没有重复,则加入到新的List中
如果新的List已经有,则使用既存的那一个
二、扩展,封装成方法
这个是尝试着封装了一下,可能存在问题
public static <T, U extends Comparable<? super U>> List<T> distinct(Collection<T> list, Function<? super T, ? extends U> fun){
return list.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(fun)))
, ArrayList::new));
}