Java Reference
In-Depth Information
You can solve the ambiguity by providing an explicit cast (Task):
doSomething((Task)() -> System.out.println("Danger danger!!"));
Don't be turned off by these issues though; there's good news! Most integrated development
environments (IDEs) such as NetBeans and IntelliJ support this refactoring and will
automatically ensure these gotchas don't arise.
8.1.3. From lambda expressions to method references
Lambda expressions are great for short code that needs to be passed around. But consider using
method references when possible to improve code readability. A method name states more
clearly the intent of your code. For example, in chapter 6 we showed you the following code to
group dishes by caloric levels:
Map<CaloricLevel, List<Dish>> dishesByCaloricLevel =
menu.stream()
.collect(
groupingBy(dish -> {
if (dish.getCalories() <= 400) return CaloricLevel.DIET;
else if (dish.getCalories() <= 700) return CaloricLevel.NORMAL;
else return CaloricLevel.FAT;
}));
You can extract the lambda expression into a separate method and pass it as argument to
groupingBy. The code becomes more concise and its intent is now more explicit:
You need to add the method getCaloricLevel inside the Dish class itself for this to work:
public class Dish{
...
public CaloricLevel getCaloricLevel(){
if (this.getCalories() <= 400) return CaloricLevel.DIET;
 
Search WWH ::




Custom Search