实体类:
public class Student {
private String name;
private int age;
private String sex;
Student(String name,int age,String sex){
this.name = name;
this.age = age;
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
list去重复
List list = new ArrayList<>();
list.add(new Student(“小A”,12,“男”));
list.add(new Student(“小B”,13,“男”));
list.add(new Student(“小C”,14,“男”));
list.add(new Student(“小D”,13,“女”));
list.add(new Student(“小A”,15,“女”));
list.add(new Student(“小D”,14,“男”));
list.add(new Student(“小A”,12,“男”));
System.out.println(“原数据===” + JSON.toJSONString(list));
//按照名字去除重复
List resultList = list.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(s -> s.getName()))), ArrayList::new));
System.out.println(“按名字去除重复数据===” + JSON.toJSONString(resultList));
//按照名字和年龄去除重复
List resultList2 = list.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(
Comparator.comparing(s -> s.getName() + “;” + s.getAge()))), ArrayList::new));
System.out.println(“按照名字和年龄去除重复数据===” + JSON.toJSONString(resultList2));
输出结果:
原数据===[{“age”:12,“name”:“小A”,“sex”:“男”},{“age”:13,“name”:“小B”,“sex”:“男”},{“age”:14,“name”:“小C”,“sex”:“男”},{“age”:13,“name”:“小D”,“sex”:“女”},{“age”:15,“name”:“小A”,“sex”:“女”},{“age”:14,“name”:“小D”,“sex”:“男”},{“age”:12,“name”:“小A”,“sex”:“男”}]
按名字去除重复数据===[{“age”:12,“name”:“小A”,“sex”:“男”},{“age”:13,“name”:“小B”,“sex”:“男”},{“age”:14,“name”:“小C”,“sex”:“男”},{“age”:13,“name”:“小D”,“sex”:“女”}]
按照名字和年龄去除重复数据===[{“age”:12,“name”:“小A”,“sex”:“男”},{“age”:15,“name”:“小A”,“sex”:“女”},{“age”:13,“name”:“小B”,“sex”:“男”},{“age”:14,“name”:“小C”,“sex”:“男”},{“age”:13,“name”:“小D”,“sex”:“女”},{“age”:14,“name”:“小D”,“sex”:“男”}]