Jerome Ryan Villamor
Posted on April 24, 2023
Method reference is a good way to reduce the noise inside our Java streams.
Say that we have a list of names, and we want to map each of them to full name. We can achieve that by using the code below:
public void example() {
List <String> names = Arrays.asList("Jerome", "Steve", "Cathy", "Lara");
names.stream()
.map((String name) -> {
User user = repository.getUser(name);
String fullname = user.firstname + " " + user.lastname;
return fullname;
})
.forEach((String name) -> System.out.println(name));
}
Streams are not good for readability if your lambda methods contain many lines of codes. I prefer to have a rule of thumb that if it's 3 or more lines then we need to extract the code to its dedicated method.
public String getFullname(String name) {
User user = repository.getUser(name);
String fullName = user.firstname + " " + user.lastname;
return fullname;
}
Then use method reference to make our stream more concise and shorter.
public void example() {
List <String> names = Arrays.asList("Jerome", "Steve", "Cathy", "Lara");
names.stream()
.map(this::getFullname)
.forEach((String name) - > System.out.println(name));
}
Note that a properly name method will make a difference. A code map(this::getFullname)
can read as an English sentence. That's a sign of a cleaner and better code.
Posted on April 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 28, 2024