-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
60 lines (47 loc) · 1.67 KB
/
Main.java
File metadata and controls
60 lines (47 loc) · 1.67 KB
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
package com.dj;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class Main {
record Person(String firstName, String lastName) {
@Override
public String toString() {
return firstName + " " + lastName;
}
}
public static void main(String[] args) {
List<Person> people = new ArrayList<>(Arrays.asList(
new Main.Person("Lucy", "Van Pelt"),
new Person("Sally", "Brown"),
new Person("Linus", "Van Pelt"),
new Person("Peppermint", "Patty"),
new Person("Charlie", "Brown")
));
//Using anonymous class
var comparatorLastName = new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
return o1.lastName.compareTo(o2.lastName);
}
};
people.sort((o1, o2) -> o1.lastName.compareTo(o2.lastName));
System.out.println(people);
interface EnhancedComparator<T> extends Comparator<T> {
int secondLevel(T o1, T o2);
}
var comparatorMixed = new EnhancedComparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
int result = o1.lastName().compareTo(o2.lastName());
return (result == 0 ? secondLevel(o1, o2) : result);
}
@Override
public int secondLevel(Person o1, Person o2) {
return o1.firstName().compareTo(o2.firstName());
}
};
people.sort(comparatorMixed);
System.out.println(people);
}
}