Skip to content

Commit aee2ec4

Browse files
committed
Sandbox. Woman comparators.
1 parent 19aa224 commit aee2ec4

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

SandBox/src/com/rakitov/sandbox/comparators2/Main.java

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package com.rakitov.sandbox.comparators2;
22

33
import java.util.ArrayList;
4+
import java.util.Collections;
45
import java.util.Comparator;
56
import java.util.List;
67

@@ -14,13 +15,37 @@ public static void main(String[] args) {
1415
women.add(new Woman("Kate", 34, 168, 67, 2));
1516
women.add(new Woman("Jackie", 44, 183, 57, 1));
1617

18+
// Anonymous new Comparator<Woman>() can be replaced with lambda
19+
Comparator<Woman> compareByName = new Comparator<Woman>() {
20+
@Override
21+
public int compare(Woman w1, Woman w2) {
22+
return w1.getName().compareTo(w2.getName());
23+
}
24+
};
25+
// Like this, but it Can be replaced with 'Comparator.comparing'
26+
Comparator<Woman> compareByNameLambda = (w1, w2) -> w1.getName().compareTo(w2.getName());
27+
// Can be replaced with 'Comparator.comparing'
28+
Comparator<Woman> compareByNameComparator = Comparator.comparing(Woman::getName);
1729

18-
Comparator<Woman> compareByHeight = Comparator.comparingInt(Woman::getHeight);
30+
31+
// Lambda can be replaced with method reference
32+
Comparator<Woman> compareByHeight = Comparator.comparingInt(woman -> woman.getHeight());
1933

2034
System.out.println("Before sort");
2135
women.forEach(System.out::println);
22-
System.out.println("\nAfter sort");
23-
women.sort(compareByHeight);
36+
System.out.println("\nAfter sort height");
37+
38+
// Collections.sort could be replaced with List.sort
39+
Collections.sort(women, compareByHeight);
40+
women.forEach(System.out::println);
41+
System.out.println("\nAfter sort weight");
42+
// Can sort like this too.
43+
// and another way to make a comparator
44+
women.sort(Comparator.comparingInt(Woman::getWeight));
45+
women.forEach(System.out::println);
46+
47+
System.out.println("\nAfter name sort");
48+
women.sort(compareByName);
2449
women.forEach(System.out::println);
2550

2651
}

SandBox/src/com/rakitov/sandbox/comparators2/Woman.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ public void setChildren(int children) {
6969

7070
@Override
7171
public String toString() {
72-
return String.format("%s is %d years old. Height: %d kg. Weight: %d cm. Number of " +
72+
return String.format("%s is %d years old. Weight: %d kg. Height: %d cm. Number of " +
7373
"children: %d",
74-
name, age, height, weight, children);
74+
name, age, weight, height, children);
7575
}
7676
}

0 commit comments

Comments
 (0)