package com.baiyou.deWeight;
public class Student {
private Integer stuNum; // 学号
private String name; // 姓名
private Integer age; // 年龄
public Integer getStuNum() {
return stuNum;
}
public void setStuNum(Integer stuNum) {
this.stuNum = stuNum;
}
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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((stuNum == null) ? 0 : stuNum.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (stuNum == null) {
if (other.stuNum != null)
return false;
} else if (!stuNum.equals(other.stuNum))
return false;
return true;
}
}
package com.baiyou.deWeight;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class Test {
public static List<Student> stuList() {
List<Student> stuList = new ArrayList<Student>();
Student stu1 = new Student();
stu1.setStuNum(20180823);
stu1.setName("张三");
stu1.setAge(20);
stuList.add(stu1);
Student stu2 = new Student();
stu2.setStuNum(20180824);
stu2.setName("李四");
stu2.setAge(21);
stuList.add(stu2);
Student stu3 = new Student();
stu3.setStuNum(20180825);
stu3.setName("李四");
stu3.setAge(21);
stuList.add(stu3);
Student stu4 = new Student();
stu4.setStuNum(20180826);
stu4.setName("张五");
stu4.setAge(22);
stuList.add(stu4);
return stuList;
}
public static void main(String[] args) {
List<Student> stuList = stuList();
//去重
List<Student> distinctClass = stuList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + ";" + o.getAge()))), ArrayList::new));
System.out.println("之前stuList集合中的数据");
stuList.forEach((Student s) -> System.out.println(s.getName() + "--->" + s.getAge()));
System.out.println("原有stuList集合中的数据");
distinctClass.forEach((Student s) -> System.out.println(s.getName() + "--->" + s.getAge()));
}
}
![](https://img-blog.csdnimg.cn/2021062319015782.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MjEyMTU1Nw==,size_16,color_FFFFFF,t_70)