6. Before Lambda
List<Employee> employees = ...
double highestSalary = 0.0;
for (Employee e : employees) {
if (e.year == 2016) {
if (e.salary > highestSalary) {
highestSalary = e.salary;
}
}
}
• Client controls iteration
• Inherently serial: iterate from
beginning to end
• Not thread-safe
7. After Lambda
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• More readable
• More abstract
• Less error-prone
• No reliance on mutable state
• Easier to make parallel
8. What is Lambda?
• Lambda expressions represent anonymous functions
– Like a method, has a typed argument list, a return type, a set of thrown exceptions, and
a body
– Not associated with a class
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
Predicate
Function
9. What is Lambda?
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max();
• Stream<T> filter(Predicate<? super T> predicate)
• Filter objects that match a Predicate object
• <R> Stream<R> map(Function<? super T, ? extends R> mapper)
• Map objects to another value as specified by a Function object
Predicate
Function
10. What is Functional programming?
• Functional languages view programs as an entity— called a function—
that accepts inputs and produces output
• Functions are connected together by their outputs to other functions’
inputs.
• Underlying approach: “Evaluate an expression. Then use the results for
something else.”
11. Example
Runnable r = new Runnable(){
public void run(){
System.out.println("Hello World");
}
};
Runnable r =()-> System.out.println("Hello World");
13. What is Stream?
• A Typed Interface.
public interface Stream<T> extends BaseStream<T,Stream<T>>
• Abstraction for specifying aggregate computations
– Not a data structure
– Can be infinite
• Simplifies the description of aggregate computations
– Exposes opportunitires for optimisation
– Fusing, laziness and parrallelism
14. What is Stream?
• What can I do with it?
Answer: efficiently process high volumes of data, but also small ones.
• What does efficiently mean?
Two things:
1. In parallel, to leverage multicore CPU
2. In pipeline, to avoid the computation of intermediate data structures
15. Stream Pipeline
A stream pipeline consists of three types of things
1. A source
2. Zero or more intermediate operations
3. A terminal operation
List<Employee> employees = ...
double highestSalary = employees.stream()
.filter(Employee e-> e.getYear() == 2016)
.map(e -> e.getSalary())
.max(); Intemediate
Operation
Source
Terminal
Operation
Intemediate
Operations
27. Contact
For any question
Email: M.Haque@cimsolutions.nl
Follow me in following site:
Stackoverflow
http://stackoverflow.com/users/1265660/masud
Github
https://github.com/masudcse05
Blog
https://masudulhaque.wordpress.com