0%

List排序

前言:List排序

基础类型排序

对基础类型(包装类)的排序

1
2
3
4
5
6
7
8
9
10
11
List<Long> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(Math.round(Math.random()*10));
}
// 升序
Collections.sort(list);
// 降序
Collections.sort(list,Collections.reverseOrder());
for (Long i : list) {
System.out.println(i);
}

对象排序

第一种方法,对象继承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
public class Main {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new User(i));
}
Collections.sort(list);
for (User user : list) {
System.out.println(user.id);
}
}

static class User implements Comparable {
int id;

public User() {
}

public User(int id) {
this.id = id;
}
// 升序:this > o,返回1;相等返回0;this < o,返回-1
// 降序:this > o,返回-1;相等返回0;this < o,返回1
@Override
public int compareTo(Object o) {
User user = (User) o;
if (id > user.id) {
return 1;
} else if (id == user.id) {
return 0;
} else {
return -1;
}
}
}
}

第二种方法,在Collections.sort方法中重写compare方法

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
public class Main {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
list.add(new User(i));
}
Collections.sort(list, new Comparator<User>() {
// 升序:o1 > o2,返回1;相等返回0;o1 < o2,返回-1
// 降序:o1 > o2,返回-1;相等返回0;o1 < o2,返回1
@Override
public int compare(User o1, User o2) {
if (o1.id > o2.id) {
return 1;
} else if (o1.id == o2.id) {
return 0;
} else {
return -1;
}
}
});
for (User user : list) {
System.out.println(user.id);
}
}

static class User {
private int id;

public User() {
}

public User(int id) {
this.id = id;
}

}
}

List<Map<String,String>>排序

1
2
3
4
5
6
// 一定要注意字符串比较即compareTo方法排序规则有特殊之处即 "111"小于"22"
Collections.sort(listName, new Comparator<Map<String, String>>() {
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o1.get("key").compareTo(o2.get("key"));
}
});

compareTo方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;

int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2;
}
k++;
}
return len1 - len2;
}
-------------本文结束感谢您的阅读-------------