Collections.sort()的使用

String、Integer等基本类型已经实现了Comparable接口,可以直接使用Collections.sort()进行排序。

1
2
3
4
5
static List<Integer> intList = Arrays.asList(2, 3, 1);
// ...
Collections.sort(intList);

// 输出 1,2,3

默认为正序排序,若想自定义排序,可以自己实现Comparator接口的compare方法。

1
2
3
4
5
6
7
8
9
10
11
Coolections.sort(intList, new Comparator<Integer>() {

@Override
public int compare(Integer o1, Integer 02) {
// 返回值为int,大于0表示正序,小于0表示逆序
return o1-o1;
}

});

// 输出 3,2,1

接下来是自定义类的排序,自定义一个类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
public class Emp {
private int empno;
private String ename;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}

public Emp(int empno, String ename) {
super();
this.empno = empno;
this.ename = ename;
}
@Override
public String toString()
{
return "empno:\t"+empno+"\tename:\t"+ename;
}
}

首先直接使用Collections.sort()进行排序

1
2
3
4
5
6
7
8
9
10
static List<Emp> empList;
static
{
Emp emp1 = new Emp(2,"Guan YunChang");
Emp emp2 = new Emp(3,"Zhang Fei");
Emp emp3 = new Emp(1,"Liu Bei");
empList = Arrays.asList(emp1,emp2,emp3);
}
// ...
Collections.sort(empList);

此时会报错:

The method sort(List) in the type Collections is not applicable for the arguments (List)

意思是参数类型为List时,sort方法无法执行,原因是泛型没有继承Comparable接口。让Emp类实现Comparable接口并实现compareTo方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class Emp implements Comparable<Emp>{
private int empno;
private String ename;
public int getEmpno() {
return empno;
}
public void setEmpno(int empno) {
this.empno = empno;
}
public String getEname() {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}

public Emp(int empno, String ename) {
super();
this.empno = empno;
this.ename = ename;
}
@Override
public int compareTo(@NonNull Emp another) {
// 按员工姓名逆序排序
return another.getEname().compareTo(this.getEname());
}

@Override
public String toString()
{
return "empno:\t"+empno+"\tename:\t"+ename;
}
}

// 这时候调用
Collections.sort(empList);
// 输出
// Zhang Fei
// Liu Bei
// Guan YunChang

或者使用第二个方法,调用Collections.sort(List, new Comparator() {});方法,并实现comparator的compare方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 调用的时候
Collections.sort(empList, new Comparator<Emp>() {

@Override
public int compare(Emp e1, Emp e2) {
// 按员工姓名正序排序
return e1.getEname().compareTo(e2.getEname());
}

});

// 输出
// Guan YunChang
// Liu Bei
// Zhang Fei

总结:

1.对于String或Integer这些已经实现Comparable接口的类来说,可以直接使用Collections.sort方法传入list参数来实现默认方式(正序)排序;

2.如果不想使用默认方式(正序)排序,可以通过Collections.sort传入第二个参数类型为Comparator来自定义排序规则;

3.对于自定义类型(如本例子中的Emp),如果想使用Collections.sort的方式一进行排序,可以通过实现Comparable接口的compareTo方法来进行,如果不实现,则参考第2点;

0%