-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCustomizedComparator.java
More file actions
47 lines (37 loc) · 940 Bytes
/
CustomizedComparator.java
File metadata and controls
47 lines (37 loc) · 940 Bytes
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
// customized Comparator, I want deceading order
// 1. Collections.reverseOrder()
PriorityQueue<Integer> pq = new PriorityQueue<>(Collections.reverseOrder());
//2. Top-level class
class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
...
}
}
Collections.sort(students, new MyComparator());
// 3. Static nested class
class Solution {
private static class MyComparator implements Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
...
}
}
}
// 4, Anonymous class
Collections.sort(students, new Comparator<Student> {
@Override
public int compare(Student s1, Student s2) {
...
}
});
// Lambda expressions
Collections.sort(students, (s1, s2) -> s1.getName().compareTo(s2.getName()));
Collections.sort(students, (s1, s2) -> {
if(s1.getAge() == s2.getAge()) {
return 0;
}
else {
return s1.getAge() < s2.getAge() ? -1 : 1;
}
});