1:根据对象的属性去重(通过TreeSet、map等方式,支持多个属性去重)
package com.itsource.enjoy.util;
import com.itsource.enjoy.domain.entity.Student;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 根据集合中的某属性去重
*/
public class ListUtils {
public static void main(String[] args) {
//模拟数据
List<Student> students = new ArrayList<Student>(){{
add(new Student().setAge(27).setName("帅哥").setSex(true));
add(new Student().setAge(19).setName("校花").setSex(false));
add(new Student().setAge(18).setName("校花").setSex(false));
}};
//方式一:根据name去重 用 collectingAndThen
List<Student> list1 = students.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new));
//[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]
//扩展:根据多个字段去重
List<Student> unique = students.stream().collect(
Collectors. collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(student -> student.getName() + ";" + student.getAge()))), ArrayList::new));
//[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=18, sex=false, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]
//方式二:根据name去重 转化为map然后再转回list
Map<String, Student> studentMap = students.stream().collect(Collectors.toMap(Student::getName, Function.identity(), (k1, k2) -> k1));
List<Student> list2 = studentMap.values().stream().collect(Collectors.toList());
//[Student(name=帅哥, age=27, sex=true, birthDay=null, scores=null, status=null), Student(name=校花, age=19, sex=false, birthDay=null, scores=null, status=null)]
}
}
package com.itsource.enjoy.domain.entity;
import lombok.Data;
import lombok.experimental.Accessors;
import java.util.Date;
import java.util.List;
/**
* 学生类
*/
@Accessors(chain = true)
@Data
public class Student {
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private Integer age;
/**
* 性别
*/
private Boolean sex;
/**
* 生日
*/
private Date birthDay;
/**
* 成绩集合
*/
private List<Score> scores;
/**
* 状态类型
*/
private String status;
}