Java基础之年龄、姓名排序

问题:一个ArrayList集合里有很多person类的实例,如何通过年龄和姓名对这些类进行排序。

 

 

法一:

  通过Collections提供的sort方法进行排序,通过实现Comparator 接口重写compare方法;

 1 import java.util.*;
 2 
 3 public class Person  {
 4     public int age;
 5     public String name;
 6 
 7     public Person() {
 8     }
 9 
10     public Person(String name, int age) {
11         this.name = name;
12         this.age = age;
13     }
14 
15 
16     @Override
17     public String toString() {
18         return "Person{" +
19                 "age=" + age +
20                 ", name='" + name + '\'' +
21                 '}';
22     }
23 
24     public static void main(String[] args) {
25         ArrayList<Person> people = new ArrayList<>();
26 
27         people.add(new Person("1", 18));
28         people.add(new Person("2", 18));
29         people.add(new Person("4", 19));
30         people.add(new Person("3", 19));
31         people.add(new Person("6", 17));
32         people.add(new Person("5", 17));
33         people.add(new Person("8", 20));
34         people.add(new Person("7", 20));
35 
36         Collections.sort(people, new Comparator<Person>() {
37             @Override
38             public int compare(Person o1, Person o2) {
39                 if (o1.age - o2.age != 0)
40                     return o2.age - o1.age;
41                 return o2.name.compareTo(o1.name);
42             }
43         });
44         System.out.println(people);
45 
46     }
47 }

 

法二:

  对象直接调用sort()方法,用Lambda表达式(其实是和上面的一样的)

 1 import java.util.*;
 2 
 3 public class Person  {
 4     public int age;
 5     public String name;
 6 
 7     public Person() {
 8     }
 9 
10     public Person(String name, int age) {
11         this.name = name;
12         this.age = age;
13     }
14 
15     @Override
16     public String toString() {
17         return "Person{" +
18                 "age=" + age +
19                 ", name='" + name + '\'' +
20                 '}';
21     }
22 
23     public static void main(String[] args) {
24         ArrayList<Person> people = new ArrayList<>();
25 
26         people.add(new Person("1", 18));
27         people.add(new Person("2", 18));
28         people.add(new Person("4", 19));
29         people.add(new Person("3", 19));
30         people.add(new Person("6", 17));
31         people.add(new Person("5", 17));
32         people.add(new Person("8", 20));
33         people.add(new Person("7", 20));
34 
35         people.sort(((o1, o2) -> {if (o1.age - o2.age != 0)
36             return o1.age - o2.age;
37             return o1.name.compareTo(o2.name);}));
38 
39         System.out.println(people);
40 
41     }
42 }

 

posted on 2020-12-04 16:41  adax  阅读(796)  评论(0编辑  收藏  举报

导航