Chapter 5.8.4 – Java 8 Lambda Expressions | Introduction to Programming Using Java

Chapter 5.8.4 – Java 8 Lambda Expressions | Introduction to Programming Using Java

 

5.8.4 Java 8 Lambda Expressions

 

Chapter 5.8.4 - Java 8 Lambda Expressions | Introduction to Programming Using Java

 

The syntax for anonymous classes is cumbersome. In many cases, an anonymous class implements an interface that defines just one method. Java 8 introduces a new syntax that can be used in place of the anonymous class in that circumstance: the lambda expression. Here is what the previous subroutine call looks like using a lambda expression: drawTwice( firstG, secondG, g -> g.drawOval(10,10,100,100) )

The lambda expression is g -> g.drawOval(10,10,100,100). Its meaning is, “the method that has a parameter g and executes the code g.drawOval(10,10,100,100).” The computer knows that g is of type Graphics because it is expecting a Drawable as the actual parameter, and the only method in the Drawable interface has a parameter of type Graphics. Lambda expressions can only be used in places where this kind of type inference can be made. The general syntax of a lambda expression is hformal-parameter-listi -> hmethod-bodyi

where the hmethod bodyi can be a single expression, a single subroutine call, or a block of statements enclosed between { and }. When the body is a single expression or function call, the value of the expression is automatically used as the return value of the method that is being defined.

 

Chapter 5.8.4 - Java 8 Lambda Expressions | Introduction to Programming Using Java

 

The parameter list in the lambda expression does not have to specify the types of the parameters, although it can. Parentheses around the parameter list are optional if there is exactly one parameter and no type is specified for the parameter; this is the form seen in the example above. For a method with no parameters, the parameter list is just an empty set of parentheses. Here are a few more examples of lambda expressions:

 

Chapter 5.8.4 - Java 8 Lambda Expressions | Introduction to Programming Using Java

 

As you can see, the syntax can still get pretty complicated. There is quite a lot more to say about lambda expressions, but my intention here is only to briefly introduce one of the most interesting new features in Java 8.

 

 

java 8 lambda expressions

 

 

 

Read More…

Introduction to Programming Using Java – David J. Eck

Chapter 5.2.2 – Constructors | Introduction to Programming Using Java

Chapter 5.5.3 – Example: Vehicles | Introduction to Programming Using Java

Chapter 5.6 – This and Super | Introduction to Programming Using Java

Chapter 5.7 – Interfaces | Introduction to Programming Using Java

Chapter 5.8 – Nested Classes | Introduction to Programming Using Java

1 thought on “Chapter 5.8.4 – Java 8 Lambda Expressions | Introduction to Programming Using Java”

Leave a Comment