package 集合; import 重写equals和hashcode.Student; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class TestList { static List<User> list = new ArrayList<User>(); static User user = new User(1, "李瑜", 24); static User user1 = new User(2, "吴建", 26); static User user2 = new User(3, "吴建", 25); public static void main(String[] args) { testDistinct2(); //list.forEach(System.out::println); } /** * 集合遍历 * https://destiny1020.blog.youkuaiyun.com/article/details/40340291 */ public void traverse() { list.add(user); list.add(user1); list.forEach(user -> System.out.println(user.toString())); //list.forEach(System.out::println); } /** * 排序 * https://blog.youkuaiyun.com/qq_30869501/article/details/85242607 */ public void sort() { list.add(user); list.add(user1); list.add(user2); System.out.println("排序前"); list.forEach(User -> System.out.println(User.toString())); list.sort(new Comparator<User>() { @Override public int compare(User o1, User o2) { return o2.getAge() - o1.getAge(); } }); System.out.println("排序后"); list.forEach(User -> System.out.println(User.toString())); } /** * 集合去重(引用对象) */ private static void testDistinct2() { //引用对象的去重,引用对象要实现hashCode和equal方法,否则去重无效 Student s1 = new Student(1L, "肖战", 15, "浙江"); Student s2 = new Student(2L, "王一博", 15, "湖北"); Student s3 = new Student(3L, "杨紫", 17, "北京"); Student s4 = new Student(4L, "李现", 17, "浙江"); Student s5 = new Student(1L, "肖战", 15, "浙江"); List<Student> students = new ArrayList<>(); students.add(s1); students.add(s2); students.add(s3); students.add(s4); students.add(s5); // students.stream().distinct().forEach(System.out::println); List<Student> studentList= students.stream().distinct().collect(Collectors.toList()); studentList.forEach(student -> System.out.println(student.getName())); } }