Skip to content

Commit 6839bcf

Browse files
committed
Add examples of using max operator instead of sort and findFirst
1 parent fa07a12 commit 6839bcf

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package io.github.aplotnikov.java_8_misuses.stream.collectors;
2+
3+
import io.github.aplotnikov.java_8_misuses.domain.Client;
4+
5+
import java.util.List;
6+
7+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Good;
8+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Ugly;
9+
import static java.util.Comparator.comparingInt;
10+
11+
class TrueFunctionalApproach {
12+
@Ugly
13+
class BeforeJava8 {
14+
Client findTheOldestClient(List<Client> clients) {
15+
if (clients.isEmpty()) {
16+
return null;
17+
}
18+
19+
Client oldestClient = clients.iterator().next();
20+
for (Client client : clients) {
21+
if (client.getAge() > oldestClient.getAge()) {
22+
oldestClient = client;
23+
}
24+
}
25+
26+
return oldestClient;
27+
}
28+
}
29+
30+
@Ugly
31+
class NaiveStreamsApproach {
32+
Client findTheOldestClient(List<Client> clients) {
33+
return clients.stream()
34+
.sorted(comparingInt(Client::getAge))
35+
.findFirst()
36+
.orElse(null);
37+
}
38+
}
39+
40+
@Ugly
41+
class StreamsWithReduction {
42+
Client findTheOldestClient(List<Client> clients) {
43+
return clients.stream()
44+
.reduce((firstClient, secondClient) ->
45+
firstClient.getAge() > secondClient.getAge() ? firstClient : secondClient
46+
)
47+
.orElse(null);
48+
}
49+
}
50+
51+
@Good
52+
class MaxWithComparator {
53+
Client findTheOldestClient(List<Client> clients) {
54+
return clients.stream()
55+
.max(comparingInt(Client::getAge))
56+
.orElse(null);
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)