lambda expressions java8 - yousry
TRANSCRIPT
Lambda expressions Overview
Yousry IbrahimApril 27, 2016
2
Agenda• What is the meaning of Lambda?• Functional interface.• Examples with built-in interfaces.• Traversing collections with lambda.• Example with new Interface.
What is the meaning of Lambda?
3
–In the computer science lambda means function without a name.
–So it opens the door to functional programming.–Lambda let you define a Class with a single method or function with a special easy syntax.
4
Functional interface
- In the quote for an early specs for lambda says
“Lambda expressions can only appear in places where they will be assigned to a variable whose type is a functional interface.”
http://cr.openjdk.java.net/~briangoetz/lambda/lambda-translation.html
- So Functional interfaces are These interfaces which have a single abstract method (before java 8 known as SAM Single Abstract Method )
- Some examples of Java built-in Functional interfaces :Runnable, Callable, Comparator, TimerTask
5
Examples with built-in interfaces
Runnable Interface:- Before Java8 we used to make Thread as : - Or even by anonymous class without a name of the class
- we could use the inner classes as :
6
Examples with built-in interfaces Con.
Runnable Interface:- Using Lambda Expressions with Java8 :
- As you can see the code significantly reduced and also become more readable by using lambda
– Now let me explain the syntax and what happened exactly in the previse example
- In case implementation more than one line
7
Examples with built-in interfaces Con II.
Comparator Interface:- Before Java8 we used to use Comparator in such way:
8
Examples with built-in interfaces Con III.
Comparator Interface:- Using Lambda expressions in Java8:
9
Traversing collections with lambda.
- Before Lambda we could traverse collections as below:
10
Traversing collections with lambda Con.
- Lets have a look on Array List Class:
11
Traversing collections with lambda Con II.
- So we can write the previse code using Lambda as below
12
Example with new Interface.
- We not only can used the built-in Interfaces But also can use new Interfaces with below steps:
1- Create your new Functional Interface using new annotation
2- Use your interface with Lambda Expressions:
The result is 50
13
Thank youYousry