Skip to content

Commit e814570

Browse files
committed
Add examples of avoiding forEach methods
1 parent ca75d20 commit e814570

1 file changed

Lines changed: 34 additions & 0 deletions

File tree

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package io.github.aplotnikov.java_8_misuses.stream;
2+
3+
import io.github.aplotnikov.java_8_misuses.domain.Client;
4+
5+
import java.util.List;
6+
import java.util.concurrent.atomic.AtomicInteger;
7+
8+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Good;
9+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Ugly;
10+
11+
class AvoidLoopsInStreams {
12+
13+
@Ugly
14+
class UseExternalCounter {
15+
double countAverageLoansPerClient(List<Client> clients) {
16+
if (clients.isEmpty()) {
17+
return 0;
18+
}
19+
AtomicInteger totalCount = new AtomicInteger();
20+
clients.forEach(client -> totalCount.addAndGet(client.getLoans().size()));
21+
return totalCount.doubleValue() / clients.size();
22+
}
23+
}
24+
25+
@Good
26+
class ApplyMappingsToTargetType {
27+
double countAverageLoansPerClient(List<Client> clients) {
28+
return clients.stream()
29+
.mapToDouble(client -> client.getLoans().size())
30+
.average()
31+
.orElse(0);
32+
}
33+
}
34+
}

0 commit comments

Comments
 (0)