java中Comparator的使用:对用户集合进行排序,先按照年龄大小排序,若年龄相等,则按照姓名排序
标签: <无>
public
int
compare(User u1, User u2) {
}
此方法返回一个int类型的数据,但是此int的值只能是一下三种:
1:表示大于
-1:表示小于
0:表示相等
例: 从小到大的顺序排列
public class FielNameComparator implements Comparator { @Override public int compare(Object o1, Object o2) { String fileName1 = (String) o1; String fileName2 = (String) o2; String[] aa1 = fileName1.split(".xml")[0].split("_"); String b1 = aa1[aa1.length - 1]; long l1 = Long.parseLong(b1); String[] aa2 = fileName2.split(".xml")[0].split("_"); String b2 = aa2[aa2.length - 1]; long l2 = Long.parseLong(b2); if(l1<l2) { return -1; }else if(l1>l2) { return 1; } return 0; } }
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
|
package
com.mango.compare;
public
class
User {
private
int
age;
private
String name;
public
User() {
}
public
User(
int
age, String name) {
this
.age = age;
this
.name = name;
}
public
int
getAge() {
return
age;
}
public
void
setAge(
int
age) {
this
.age = age;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
@Override
public
String toString() {
return
"User [age="
+ age +
", name="
+ name +
"]"
;
}
}
|
2. [代码][Java]代码
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
41
42
43
|
package
com.mango.compare;
import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.Comparator;
import
java.util.List;
public
class
UserComparator
implements
Comparator<User> {
public
int
compare(User u1, User u2) {
if
(u1.equals(u2)){
return
0
;
}
else
if
(u1.getAge() < u2.getAge()){
return
1
;
}
else
if
(u1.getAge() == u2.getAge()){
int
f = u1.getName().compareTo(u2.getName());
if
(f <
0
){
return
-
1
;
}
return
0
;
}
else
{
return
-
1
;
}
}
public
static
void
main(String[] args) {
List<User> users =
new
ArrayList<User>();
users.add(
new
User(
10
,
"a"
));
users.add(
new
User(
11
,
"d"
));
users.add(
new
User(
15
,
"s"
));
users.add(
new
User(
6
,
"x"
));
users.add(
new
User(
17
,
"a"
));
users.add(
new
User(
17
,
"b"
));
users.add(
new
User(
17
,
"c"
));
users.add(
new
User(
17
,
"d"
));
UserComparator comparator =
new
UserComparator();
Collections.sort(users, comparator);
for
(User u : users){
System.out.println(u);
}
}
}
|