-
Notifications
You must be signed in to change notification settings - Fork 11
/
UsingComparator.java
64 lines (56 loc) · 1.52 KB
/
UsingComparator.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package genericsAndCollections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* @author chengfeili
* Jun 7, 2017 9:14:20 PM
*
*/
public class UsingComparator implements Comparable<UsingComparator> {
private String name;
private int weight;
public UsingComparator(String name, int weight) {
this.name = name;
this.weight = weight;
}
public String getName() {
return name;
}
public int getWeight() {
return weight;
}
public String toString() {
return name;
}
public int compareTo(UsingComparator d) {
return name.compareTo(d.name);
}
public static void main(String[] args) {
Comparator<UsingComparator> byWeight = new Comparator<UsingComparator>() {
@Override
public int compare(UsingComparator d1, UsingComparator d2) {
return d1.getWeight() - d2.getWeight();
}
};
/**
* Comparator is a functional interface since there is only one abstract
* method to implement. This means that we can rewrite the comparator
* in the previous example as any of the following:
*
* Comparator<UsingComparator> comp = (a, b) -> a.getWeight() - b.getWeight();
*
*/
List<UsingComparator> ducks = new ArrayList<>();
ducks.add(new UsingComparator("Quack", 7));
ducks.add(new UsingComparator("Puddles", 10));
// Using Comparable
Collections.sort(ducks);
System.out.println(ducks); // [Puddles, Quack]
// Using Comparator
Collections.sort(ducks, byWeight);
System.out.println(ducks); // [Quack, Puddles]
}
}