需求说明:
现有对象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;}@Overridepublic 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();//比较新老对象的Idif (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;}