File tree Expand file tree Collapse file tree
src/main/java/io/github/aplotnikov/java_8_misuses/stream/collectors Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments