When using Java 8 streams I often find that I need to refactor a multi-statement lambda expression. I will illustrate this with a simple example. Assume I have started writing this code:
Stream.of(1, 3).map(i -> {
if (i == 1) {
return "I";
} else if (i == 3) {
return "E";
}
return "";
}).forEach(System.out::println);
Now I am not very fond of the large lambda expression in the map
call. Hence, I want to refactor it out of there. I see two options, either I make an instance of Function
in my class:
private static Function<Integer, String> mapper = i -> {
if (i == 1) {
return "I";
} else if (i == 3) {
return "E";
}
return "";
};
and use it like this:
Stream.of(1, 3).map(mapper).forEach(System.out::println);
Or I simply make a method:
private static String map(Integer i) {
if (i == 1) {
return "I";
} else if (i == 3) {
return "E";
}
return "";
}
and use a method reference:
Stream.of(1, 3).map(Test::map).forEach(System.out::println);
Apart from the obvious matter of taste, are there any advantages or drawbacks to either approach?
For example, I know the stack traces become more readable in the method reference case, which is a small advantage.