java对象排序(Collections.sort Comparator)
我们在一般的使用过程中对于数组、集合等的排序,如果不涉及对象的话就比较容易。一般都有现成的API方法可以直接使用。
当要对对象集合排序时候,现在基本都重写Comparator类的compare方法来实现。
public static <T> void sort(List<T> list, Comparator<? super T> c)
创建一个Student类,包含姓名、性别、身高、体重。当有许多Student时候,此时就需要一个集合包含这些对象。我们要通过身高来对这些Student排序,就要重写Comparator了。
话不多少,上代码。
创建Strudent类,生成getter、setter方法和构造方法。
1 public class Student {
2 private String name;
3 private String sex;
4 private Double height;
5 private Double weight;
6 public Student(String name, String sex, Double height, Double weight) {
7 this.name = name;
8 this.sex = sex;
9 this.height = height;
10 this.weight = weight;
11 }
12 public String getName() {
13 return name;
14 }
15
16 public void setName(String name) {
17 this.name = name;
18 }
19
20 public String getSex() {
21 return sex;
22 }
23
24 public void setSex(String sex) {
25 this.sex = sex;
26 }
27
28 public Double getHeight() {
29 return height;
30 }
31
32 public void setHeight(Double height) {
33 this.height = height;
34 }
35
36 public Double getWeight() {
37 return weight;
38 }
39
40 public void setWeight(Double weight) {
41 this.weight = weight;
42 }
43
44 }
创建List<Student>,并进行排序
1 public static void main(String[] args) throws Exception{
2 Student xiaoMing = new Student("Xiao Ming", "Male", 175.25d, 65.5d);
3 Student xiaoHong = new Student("Xiao Hong", "Female", 165.1d, 50.12d);
4 Student xiaoLi = new Student("Xiao Li", "Female", 180.5d, 70.12d);
5 List<Student> list = new ArrayList<>();
6 list.add(xiaoMing);
7 list.add(xiaoLi);
8 list.add(xiaoHong);
9 for(Student s : list) {
10 System.out.println(s.getName());
11 }
12 System.out.println("=================开始排序==============");
13 Collections.sort(list, new Comparator<Student>() {
14 @Override
15 //关于返回值,此处有高人说明:返回1表示true,需要调整顺序,返回-1表示false不需要排序,不必纠结升序还是降序,你只要关系你需要不需要调整顺序即可
16 public int compare(Student s1, Student s2) {
17 if (s1.getHeight().compareTo(s2.getHeight()) > 0) {
18 return -1;
19 } else {
20 return 1;
21 }
22 }
23 });
24 //输出排序结果
25 for(Student s : list) {
26 System.out.println(s.getName());
27 }
28
29 }
输出结果
Xiao Ming
Xiao Li
Xiao Hong
=================开始排序==============
Xiao Li
Xiao Ming
Xiao Hong
调整返回值结果
1 Collections.sort(list, new Comparator<Student>() {
2 @Override
3 //关于返回值,此处有高人说明:返回1表示true,需要调整顺序,返回-1表示false不需要排序,不必纠结升序还是降序,你只要关系你需要不需要调整顺序即可
4 public int compare(Student s1, Student s2) {
5 if (s1.getHeight().compareTo(s2.getHeight()) > 0) {
6 return 1;
7 } else {
8 return -1;
9 }
10 }
11 });
再次运行查看结果
Xiao Ming
Xiao Li
Xiao Hong
=================开始排序==============
Xiao Hong
Xiao Ming
Xiao Li