需求说明:
现有对象Student(id,name,age),并有List<Student> students集合,要求:对students集合中的对象按age去重,并保留id较大的那个对象。
Student
public class Student {
private int id;
private String name;
private String age;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age='" + age + '\'' +
'}';
}
}
实现代码:
public static void main(String[] args) {
//获取集合
List<Student> students = getStudentList();
//输出当前集合
System.out.println(students);
//去重后的集合
List<Student> newStudentList = new ArrayList<>();
//去重字段和对象
HashMap<String, Student> stuMap = new HashMap<>();
//循环
students.forEach(student -> {
//出现age重复
if (stuMap.containsKey(student.getAge())) {
//老对象
int oldId = stuMap.get(student.getAge()).getId();
//新对象
int currId = student.getId();
//比较新老对象的Id
if (oldId < currId) {
//如果新对象Id比较大,则保留新对象
stuMap.put(student.getAge(), student);
}
} else {
//如果没有重复的直接添加
stuMap.put(student.getAge(), student);
}
});
//把数据转移到新集合里
newStudentList.addAll(stuMap.values());
System.out.println(newStudentList);
}
private static List<Student> getStudentList() {
List<Student> students = new ArrayList<>();
Student st1 = new Student();
st1.setId(1);
st1.setName("张三");
st1.setAge("23");
students.add(st1);
Student st2 = new Student();
st2.setId(2);
st2.setName("李四");
st2.setAge("24");
students.add(st2);
Student st3 = new Student();
st3.setId(3);
st3.setName("王五");
st3.setAge("25");
students.add(st3);
Student st4 = new Student();
st4.setId(4);
st4.setName("赵六");
st4.setAge("23");
students.add(st4);
return students;
}