1. Obtain data

ArrayList<Person> list = new ArrayList<>();
Person person1 = new Person(1."Zhang".18);//int id,string name,int age
Person person2 = new Person(2."Bill".4);
Person person3 = new Person(3."Fifty".15);
Person person4 = new Person(4."Daisy".12);
Person person5 = new Person(5."Zhang".13);
Person person6 = new Person(6."Old.".20);
Person person7 = new Person(7."Old.".20);
Person person8 = new Person(6."Old ten".21); list.add(person1); list.add(person2); list.add(person3); list.add(person4); list.add(person5); list.add(person6); list.add(person7); list.add(person8);Copy the code

2. Sort objects according to their properties

2.1 Sort sort by a single attribute

list.sort((o1, o2)-> o1.getAge()-o2.getAge());
for (Person person : list) {
  System.out.println("person = " + person);
}
// The result is as follows:
Copy the code

2.2 The sort method sorts by two attributes

//.reversed() is reversed. The default is positive.list.sort(Comparator.comparing(Person::getAge).reversed().thenComparing(Comparator.comparing(Person::getId)).reversed()) ;for (Person person : list) {
  System.out.println("person = " + person);
}
// The result is as follows:
Copy the code

2.3 TreeSet sort by individual attributes

TreeSet<Person> set = new TreeSet<>
(Comparator.comparing(Person::getAge).reversed());
set.addAll(list);
for (Person person : set) {
  System.out.println("person = " + person);
}
// The result is as follows
Copy the code

2.4 TreeSet sort and remove weights based on two attributes

TreeSet<Person> set = new TreeSet<>
(Comparator.comparing(Person::getAge).reversed().thenComparing(Comparator.comparing(Person::getId)).reversed());
set.addAll(list);
for (Person person : set) {
  System.out.println("person = " + person);
}
Copy the code

PS: after you see that you can help three even messages, if there is a small partner looking for job opportunities also please private small assistant wechat X118422 detailed chat, welcome to join the three pig science and technology development group family oh ~