Skip to content

Commit d663097

Browse files
committed
Add examples with long lambdas
1 parent ab2c3a9 commit d663097

2 files changed

Lines changed: 70 additions & 1 deletion

File tree

src/main/java/io/github/aplotnikov/java_8_misuses/domain/Client.java

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,16 @@ public class Client {
1616

1717
long id;
1818

19+
String name;
20+
21+
String surname;
22+
1923
List<Loan> loans;
2024

21-
public Client(long id, List<Loan> loans) {
25+
public Client(long id, String name, String surname, List<Loan> loans) {
2226
this.id = id;
27+
this.name = name;
28+
this.surname = surname;
2329
this.loans = loans;
2430
loans.forEach(loan -> loan.setClient(Client.this));
2531
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package io.github.aplotnikov.java_8_misuses.lambda;
2+
3+
import io.github.aplotnikov.java_8_misuses.domain.Client;
4+
import lombok.Data;
5+
import lombok.experimental.FieldDefaults;
6+
7+
import java.util.List;
8+
import java.util.function.Function;
9+
10+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Good;
11+
import static io.github.aplotnikov.java_8_misuses.utils.Annotations.Ugly;
12+
import static java.util.stream.Collectors.toList;
13+
import static lombok.AccessLevel.PRIVATE;
14+
15+
class AvoidLongLambdas {
16+
17+
@Ugly
18+
class LongLambdaInPlace {
19+
List<ClientDto> convertToDto(List<Client> clients) {
20+
return clients.stream()
21+
.map(client -> {
22+
ClientDto dto = new ClientDto();
23+
dto.setId(client.getId());
24+
dto.setName(client.getName());
25+
dto.setSurname(client.getSurname());
26+
return dto;
27+
})
28+
.collect(toList());
29+
}
30+
}
31+
32+
@Good
33+
class MethodReferenceInsteadOfLambda {
34+
//particular toDto could be implemented as a separate class or as a lambda function
35+
private final Function<Client, ClientDto> toDto = this::convertToDto;
36+
37+
List<ClientDto> convertToDto(List<Client> clients) {
38+
return clients.stream()
39+
.map(toDto)
40+
.collect(toList());
41+
}
42+
43+
private ClientDto convertToDto(Client client) {
44+
ClientDto dto = new ClientDto();
45+
dto.setId(client.getId());
46+
dto.setName(client.getName());
47+
dto.setSurname(client.getSurname());
48+
return dto;
49+
}
50+
}
51+
52+
@Data
53+
@FieldDefaults(level = PRIVATE)
54+
private static class ClientDto {
55+
56+
long id;
57+
58+
String name;
59+
60+
String surname;
61+
62+
}
63+
}

0 commit comments

Comments
 (0)