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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
package map;
* Created by benjamin on 11/5/15.
*/
import java.util.Comparator;
* 谁的拼音靠前,谁就排前面.
* 然后对名字进行排序.如果同名,女性排前面.
* 如果名字和性别都相同,年龄小的排前面.
*
*
* int compare(Object o1, Object o2)返回一个基本的数据类型
* 如果要按照升序排序
* 则o1 < o2, return -1; equals return 0; o1 > 02 return 1;
* 如果要按照降序排序
* 则01 < 02, return 1; equals return 0; o1 > o2 return -1;
*
*/
public class Comparators {
* 获取合适的比较器
* @return
*/
public static Comparator getComparator() {
return new Comparator() {
@Override
public int compare(Object o1, Object o2) {
if(o1 instanceof String) {
return compare((String)o1, (String)o2);
} else if(o1 instanceof Integer) {
return compare((Integer)o1, (Integer)o2);
} else if(o1 instanceof Person) {
return comparePerson((Person) o1, (Person) o2);
} else {
System.out.println("未找到合适的比较器");
return 1;
}
}
};
}
private static int compare(String o1, String o2) {
int len1 = o1.length();
int len2 = o2.length();
int min = Math.min(len1, len2);
char v1[] = o1.toCharArray();
char v2[] = o2.toCharArray();
int pos = 0;
while(--min != 0) {
char c1 = v1[pos];
char c2 = v2[pos];
if (c1 != c2) {
return c1 - c2;
}
pos ++;
}
return len1 - len2;
}
* 比较年龄
* @param o1
* @param o2
* @return
*/
private static int compare(Integer o1, Integer o2) {
int val1 = o1.intValue();
int val2 = o2.intValue();
return val1 < val2 ? -1 : (val1 == val2 ? 0 : 1);
}
* 比较性别
* @param o1
* @param o2
* @return
*/
private static int compare(char o1, char o2) {
return ((o1 == o2) ? 0 : (o1 == '男' ? 1 : -1));
}
* 比较Person
* @param o1
* @param o2
* @return
*/
private static int comparePerson(Person o1, Person o2) {
String firstName1 = o1.getFirstName();
String firstName2 = o2.getFirstName();
String lastName1 = o1.getLastName();
String lastName2 = o2.getLastName();
char sex1 = o1.getSex();
char sex2 = o2.getSex();
Integer age1 = o1.getAge();
Integer age2 = o2.getAge();
return (compare(firstName1, firstName2) == 0 ?
(compare(lastName1, lastName2) == 0 ?
(compare(sex1, sex2) == 0 ?
(compare(age1, age2) == 0 ? 0 :
compare(age1, age2)) :
compare(sex1, sex2)) :
compare(lastName1, lastName2)) :
compare(firstName1, firstName2));
}
}
|