今天突然遇到list集合对象去重的问题,在这里记录一下解决方法,自己觉得还不错。
在list集合里去掉重复对象,只要把它强转成set集合就可以了,
List<Student> stu = new ArrayList<Student>(); stu.add(new Student("1","yi")); stu.add(new Student("3","san")); stu.add(new Student("1","yi")); stu.add(new Student("3","san")); stu.add(new Student("2","er")); stu.add(new Student("1","yi")); stu.add(new Student("3","san")); stu.add(new Student("2","er")); //set集合保存的是引用不同地址的对象 Set<Student> ts = new HashSet<Student>(); ts.addAll(stu); for (Student student : ts) { System.out.println(student.getId()+"-"+student.getName()); }
原文:https://www.cnblogs.com/lizishaoye/p/10748278.html