SlideShare a Scribd company logo
JAVA 8 REVEALED
LAMBDAS, STREAMS.
Who We are
Bazlur Rahman Rokon
Associate Software Engineer, Therap Services, LLC
Sazzadur Rahman
Software Engineer, Kona Software Lab Ltd.
What’s new in Java 8
1. Lambda Expressions
2. Method references
3. Default methods
4. Bulk Data Operation → Stream API
5. Date-Time
6. And a lot more ……
Assumption
1. We really love abstraction
2. We Actually Build cool Stuffs
3. We are programmers and lazy
4. We work only day time and go home early (Well, we have life, right
:/ )
5. Users want too many features
6. As we are lazy, we don’t want to do too much work.
7. So we love “Less code, do more” philosophy
The Best Code is No Code At All
1. Code is bad
2. It rots
3. It requires periodic maintenance
4. But the fact is, we love coding, more specifically less
coding
Lambda in Action
public interface Runnable {
public abstract void run();
}
Lambda in Action cont.
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("JUGBD Meetup 3.0");
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("JUGBD Meetup 3.0");
}
}).start();
Code I’m
interested in
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("JUGBD Meetup 3.0");
}
}).start();
Ceremony
Less code ☺
new Thread(() -> System.out.println("JUGBD Meetup 3.0"))
.start();
What is Lambda Expression
() -> { }
What is Lambda Expression
(Thing t ) -> { }
What is Lambda Expression
(Thing t ) -> { }
(Thing t , More m) -> { }
Let’s have a situation
public class Person {
private String name;
private LocalDate birthday;
private Sex gender;
private String emailAddress;
private String cellNo;
// getters and setters//
What we want to do
1. Search based on characteristics and send
email/call
1. find older than 60 -> then need Elderly allowance
2. find voters
1. kids -> less than 18 -> they are not allowed to
vote, so ignore them
2. sort by name, by age
Take # 1
public void findPersonOlder(List<Person> persons) {
for (Person p : persons) {
if (p.getAge() > 60) {
sendEmail(p.getEmailAddress());
}
}
}
Take #2
public void findEligibleVoters(List<Person> persons) {
for (Person p : persons) {
if (p.getAge() > 18) {
sendEmail(p.getEmailAddress());
}
}
}
Take # 3
public void findTargetAudienceForAd(List<Person> persons) {
for (Person p : persons) {
if (p.getAge() > 25 &&
p.getGender() == Sex.MALE) {
sendEmail(p.getEmailAddress());
}
}
}
A lots of combinations
We can keep going on and on and
on….
Lets parameterize the behavior
public interface PersonPredicate {
public boolean testPerson(Person p);
}
public void processPerson(List<Person> persons,
PersonPredicate predicate) {
for (Person p : persons) {
if (predicate.testPerson(p)) {
sendEmail(p.getEmailAddress());
}
}
}
Revisit Take #2
processPerson(persons, new PersonPredicate() {
@Override
public boolean testPerson(Person p) {
return p.getAge() > 18;
}
});
Revisit Take #3
processPerson(persons, new PersonPredicate() {
@Override
public boolean testPerson(Person p) {
return p.getAge() > 25 &&
p.getGender() == Sex.MALE;
}
});
We want to call as well
public interface PersonConsumer {
public void accept (String phoneNumber);
}
public void processPerson(List<Person> persons,
PersonPredicate predicate,
PersonConsumer consumer) {
for (Person p : persons) {
if (predicate.testPerson(p)) {
String cellNo = p.getCellNo();
consumer.accept(cellNo);
}
}
}
Lets put it a bit harder
public void processPerson(List<Person> persons,
PersonPredicate predicate,
PersonConsumer consumer) {
for (Person p : persons) {
if (predicate.testPerson(p)) {
String cellNo = p.getCellNo();
consumer.accept(cellNo);
}
}
}
public interface PersonMapper {
public String map(Person p);
}
public void processPerson(List<Person> persons,
PersonPredicate predicate,
PersonMapper mapper,
PersonConsumer consumer) {
for (Person p : persons) {
if (predicate.testPerson(p)) {
String value = mapper.map(p);
consumer.accept(value);
}
Good going ..
processPerson(persons,new PersonPredicate() {
@Override
public boolean testPerson(Person p) {
return p.getAge() > 18;
}
}, new PersonMapper() {
@Override
public String map(Person p) {
return p.getCellNo();
}
}, new PersonConsumer() {
@Override
public void accept(String value) {
call(value);
}
});
Achieved behavior parameterization
Powerfull, but verbose and clunky
Revisit the Again
processPerson(persons, new PersonPredicate() {
@Override
public boolean testPerson(Person p) {
return p.getAge() > 18;
}
});
Boilerplate code
processPerson(persons, new PersonPredicate() {
@Override
public boolean testPerson(Person p) {
return p.getAge() > 18;
}
});
We are in the age of Java 8 , lets throw
away boilerplate code
processPerson(persons,
p
return p.getAge() > 18;
);
Our first lambda
processPerson(persons, p -> p.getAge() > 18);
Lets call voters
processPerson(persons,
p -> p.getAge() > 18,
p1 -> p1.getCellNo(),
c -> call(c)
);
Functional Interface
@FunctionalInterface
public interface PersonMapper {
public String map(Person p);
}
public interface PersonPredicate {
public boolean testPerson(Person p);
}
@FunctionalInterface
public interface PersonMapper {
public String map(Person p);
}
Stream API
So we were basically doing
Source -> filter -> map -> apply
Lambda Lambda Lambda
Stream API
persons
.stream()
.filter(p-> p.getAge()>19)
.map(p-> p.getCellNo())
.forEach( c-> call(c));
What is Stream?
•A sequence of elements from a source supporting sequential and parallel
aggregate operations, While completely abstracting the details of low level
multi threading logic.
•Sources can be Any type of Collection, Array, or any I/O operation who
provides data to the Stream.
•Aggregate operations are operations to collect or extract necessary
information from a stream or collection.
What is Stream?
persons
.stream()
.filter(p-> p.getAge()>19)
.map(p-> p.getCellNo())
.forEach( c-> call(c));
Intermdediate Operation
Terminal Operation
Get Stream
Source
Pipelining
Intermdediate Operation
Intermediate Operations
map
flatMap
filter
sorted
distinct
skip
limit
Map and flatMap
List<Integer> numbers = Arrays.asList(1, 2, 3, 4);
List<List<Integer>> mapped =
numbers.stream()
.map(number -> Arrays.asList(number -1, number, number +1))
.collect(Collectors.toList());
System.out.println(mapped); //:> [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]]
List<Integer> flattened =
numbers.stream()
.flatMap(number -> Arrays.asList(number -1, number, number +1).stream())
.collect(Collectors.toList());
System.out.println(flattened); //:> [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5]
Terminal Operation
collect
allMatch
noneMatch
findFirst
findAny
reduce
forEach
allMatch and noneMatch
//Check if All of the students have distinction
Boolean hasAllStudentsWithDistinction = students.stream()
.allMatch(student -> student.getScore() > 80);
//Return true if None of the students are over distinction
Boolean hasAllStudentsBelowDistinction = students.stream()
.noneMatch(student -> student.getScore() > 80);
Reduce
Reduces the whole stream into a single value
//Summing all elements of a stream
Integer sum = numbers.stream()
.reduce(0, (x, y) -> x + y); //reduce(identity, accumulator)
Integer min = numbers.stream()
.reduce(0, Integer::min);
What about having no terminal
Operation?
persons
.stream()
.filter(p-> p.getAge()>19)
.map(p-> p.getCellNo())
Intermdediate Operation
Get Stream
Source
Pipelining Intermdediate Operation
Lazy and Eager
Did you scrolled your facebook timeline, down to the beginning?
Laziness of Stream operations
• Current era is of Big Data, Parallel Processing and being real time.
• When dealing with Big Data Laziness is a big deal.
• Stream API is inherently Lazy and based on “Process on Demand”
behavior.
Laziness of Stream operations
Stream<String> streamOfNames = students.stream()
.map(student -> {
System.out.println("In Map - " +
student.getName());
return student.getName();
});
//Just to add some delay
for (int i = 1; i <= 5; i++) {
Thread.sleep(1000);
System.out.println(i + " sec");
}
//Called a terminal operation on the stream
streamOfNames.collect(Collectors.toList());
Output:
1 sec
2 sec
3 sec
4 sec
5 sec
In Map - Tom
In Map - Chris
In Map - Dave
Short Circuit
//List of first 3 students who have age > 20
students.stream()
.filter(s -> s.getAge() > 20)
.map(Student::getName)
.limit(3)
.collect(Collectors.toList());
Thanks…

More Related Content

What's hot

Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
Naresha K
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
CodeOps Technologies LLP
 
Searching and sorting by B kirron Reddi
Searching and sorting by B kirron ReddiSearching and sorting by B kirron Reddi
Searching and sorting by B kirron Reddi
B.Kirron Reddi
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
José Paumard
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
José Paumard
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
Ankur Shrivastava
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
delimitry
 
Rxjava2 custom operator
Rxjava2 custom operatorRxjava2 custom operator
Rxjava2 custom operator
彥彬 洪
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
Dhaval Dalal
 
The Ring programming language version 1.5.2 book - Part 11 of 181
The Ring programming language version 1.5.2 book - Part 11 of 181The Ring programming language version 1.5.2 book - Part 11 of 181
The Ring programming language version 1.5.2 book - Part 11 of 181
Mahmoud Samir Fayed
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
Trisha Gee
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
Donal Fellows
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
rohit_gupta_mrt
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
José Paumard
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
RichardWarburton
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
DJ Rausch
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
Mahmoud Samir Fayed
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
Abhishek Sur
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
Bret Little
 

What's hot (20)

Evolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and EffectiveEvolving with Java - How to remain Relevant and Effective
Evolving with Java - How to remain Relevant and Effective
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 
Refactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech TalkRefactoring for Software Design Smells - Tech Talk
Refactoring for Software Design Smells - Tech Talk
 
Searching and sorting by B kirron Reddi
Searching and sorting by B kirron ReddiSearching and sorting by B kirron Reddi
Searching and sorting by B kirron Reddi
 
Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2Lambdas and Streams Master Class Part 2
Lambdas and Streams Master Class Part 2
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Python dictionary : past, present, future
Python dictionary: past, present, futurePython dictionary: past, present, future
Python dictionary : past, present, future
 
Rxjava2 custom operator
Rxjava2 custom operatorRxjava2 custom operator
Rxjava2 custom operator
 
Creating Lazy stream in CSharp
Creating Lazy stream in CSharpCreating Lazy stream in CSharp
Creating Lazy stream in CSharp
 
The Ring programming language version 1.5.2 book - Part 11 of 181
The Ring programming language version 1.5.2 book - Part 11 of 181The Ring programming language version 1.5.2 book - Part 11 of 181
The Ring programming language version 1.5.2 book - Part 11 of 181
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
The TclQuadcode Compiler
The TclQuadcode CompilerThe TclQuadcode Compiler
The TclQuadcode Compiler
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Java 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelizationJava 8, Streams & Collectors, patterns, performances and parallelization
Java 8, Streams & Collectors, patterns, performances and parallelization
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Kotlin – the future of android
Kotlin – the future of androidKotlin – the future of android
Kotlin – the future of android
 
The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202The Ring programming language version 1.8 book - Part 37 of 202
The Ring programming language version 1.8 book - Part 37 of 202
 
C# 7.0 Hacks and Features
C# 7.0 Hacks and FeaturesC# 7.0 Hacks and Features
C# 7.0 Hacks and Features
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 

Viewers also liked

Top 8 disability coordinator resume samples
Top 8 disability coordinator resume samplesTop 8 disability coordinator resume samples
Top 8 disability coordinator resume samplesoliverjawood
 
Philosophy on Scientific Teaching
Philosophy on Scientific TeachingPhilosophy on Scientific Teaching
Philosophy on Scientific TeachingJacqueline Friel
 
Top 8 grants coordinator resume samples
Top 8 grants coordinator resume samplesTop 8 grants coordinator resume samples
Top 8 grants coordinator resume samplesoliverjawood
 
Top 8 athletic coordinator resume samples
Top 8 athletic coordinator resume samplesTop 8 athletic coordinator resume samples
Top 8 athletic coordinator resume samplesoliverjawood
 
Top 8 fundraiser coordinator resume samples
Top 8 fundraiser coordinator resume samplesTop 8 fundraiser coordinator resume samples
Top 8 fundraiser coordinator resume samplesoliverjawood
 
JVM Ecosystem Languages And The Future of JVM
JVM Ecosystem Languages And The Future of JVMJVM Ecosystem Languages And The Future of JVM
JVM Ecosystem Languages And The Future of JVM
Sazzadur Rahaman
 
Ti saraswatiap
Ti saraswatiapTi saraswatiap
Ti saraswatiap
saraswatiap
 
Top 8 life enrichment coordinator resume samples
Top 8 life enrichment coordinator resume samplesTop 8 life enrichment coordinator resume samples
Top 8 life enrichment coordinator resume samplesoliverjawood
 
Top 8 editorial coordinator resume samples
Top 8 editorial coordinator resume samplesTop 8 editorial coordinator resume samples
Top 8 editorial coordinator resume samplesoliverjawood
 
Smart Card to the Cloud for Convenient, Secured NFC Payment
Smart Card to the Cloud for Convenient, Secured NFC PaymentSmart Card to the Cloud for Convenient, Secured NFC Payment
Smart Card to the Cloud for Convenient, Secured NFC Payment
Sazzadur Rahaman
 
Top 8 irb coordinator resume samples
Top 8 irb coordinator resume samplesTop 8 irb coordinator resume samples
Top 8 irb coordinator resume samplesoliverjawood
 

Viewers also liked (14)

Top 8 disability coordinator resume samples
Top 8 disability coordinator resume samplesTop 8 disability coordinator resume samples
Top 8 disability coordinator resume samples
 
Philosophy on Scientific Teaching
Philosophy on Scientific TeachingPhilosophy on Scientific Teaching
Philosophy on Scientific Teaching
 
a&n_LookBook
a&n_LookBooka&n_LookBook
a&n_LookBook
 
Top 8 grants coordinator resume samples
Top 8 grants coordinator resume samplesTop 8 grants coordinator resume samples
Top 8 grants coordinator resume samples
 
RS_LookBook
RS_LookBookRS_LookBook
RS_LookBook
 
Angus Lindt
Angus LindtAngus Lindt
Angus Lindt
 
Top 8 athletic coordinator resume samples
Top 8 athletic coordinator resume samplesTop 8 athletic coordinator resume samples
Top 8 athletic coordinator resume samples
 
Top 8 fundraiser coordinator resume samples
Top 8 fundraiser coordinator resume samplesTop 8 fundraiser coordinator resume samples
Top 8 fundraiser coordinator resume samples
 
JVM Ecosystem Languages And The Future of JVM
JVM Ecosystem Languages And The Future of JVMJVM Ecosystem Languages And The Future of JVM
JVM Ecosystem Languages And The Future of JVM
 
Ti saraswatiap
Ti saraswatiapTi saraswatiap
Ti saraswatiap
 
Top 8 life enrichment coordinator resume samples
Top 8 life enrichment coordinator resume samplesTop 8 life enrichment coordinator resume samples
Top 8 life enrichment coordinator resume samples
 
Top 8 editorial coordinator resume samples
Top 8 editorial coordinator resume samplesTop 8 editorial coordinator resume samples
Top 8 editorial coordinator resume samples
 
Smart Card to the Cloud for Convenient, Secured NFC Payment
Smart Card to the Cloud for Convenient, Secured NFC PaymentSmart Card to the Cloud for Convenient, Secured NFC Payment
Smart Card to the Cloud for Convenient, Secured NFC Payment
 
Top 8 irb coordinator resume samples
Top 8 irb coordinator resume samplesTop 8 irb coordinator resume samples
Top 8 irb coordinator resume samples
 

Similar to Java 8 revealed

Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
Skills Matter
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mark Needham
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
Sharon Rozinsky
 
Kpi driven-java-development-fn conf
Kpi driven-java-development-fn confKpi driven-java-development-fn conf
Kpi driven-java-development-fn conf
Anirban Bhattacharjee
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy codeShriKant Vashishtha
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
Pete McFarlane
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
tdc-globalcode
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
Derek Willian Stavis
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
Moaid Hathot
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
Naresha K
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
arishmarketing21
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
Buddhini Seneviratne
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
Buddhini Seneviratne
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
WSO2
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
J On The Beach
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
Nicola Pedot
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
Codemotion
 

Similar to Java 8 revealed (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#Mixing Functional and Object Oriented Approaches to Programming in C#
Mixing Functional and Object Oriented Approaches to Programming in C#
 
Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#Mixing functional and object oriented approaches to programming in C#
Mixing functional and object oriented approaches to programming in C#
 
Java 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually useJava 8 new features or the ones you might actually use
Java 8 new features or the ones you might actually use
 
Kpi driven-java-development-fn conf
Kpi driven-java-development-fn confKpi driven-java-development-fn conf
Kpi driven-java-development-fn conf
 
Working effectively with legacy code
Working effectively with legacy codeWorking effectively with legacy code
Working effectively with legacy code
 
How to write code you won't hate tomorrow
How to write code you won't hate tomorrowHow to write code you won't hate tomorrow
How to write code you won't hate tomorrow
 
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
TDC2016POA | Trilha Programacao Funcional - Ramda JS como alternativa a under...
 
Ramda, a functional JavaScript library
Ramda, a functional JavaScript libraryRamda, a functional JavaScript library
Ramda, a functional JavaScript library
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
Best of build 2021 - C# 10 & .NET 6
Best of build 2021 -  C# 10 & .NET 6Best of build 2021 -  C# 10 & .NET 6
Best of build 2021 - C# 10 & .NET 6
 
Evolving with Java - How to Remain Effective
Evolving with Java - How to Remain EffectiveEvolving with Java - How to Remain Effective
Evolving with Java - How to Remain Effective
 
please help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdfplease help with java questionsJAVA CODEplease check my code and.pdf
please help with java questionsJAVA CODEplease check my code and.pdf
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Java 8 ​and ​Best Practices
 Java 8 ​and ​Best Practices Java 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Lazy Java
Lazy JavaLazy Java
Lazy Java
 
Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018Mario Fusco - Lazy Java - Codemotion Milan 2018
Mario Fusco - Lazy Java - Codemotion Milan 2018
 

Recently uploaded

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
Fermin Galan
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 

Recently uploaded (20)

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604Orion Context Broker introduction 20240604
Orion Context Broker introduction 20240604
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 

Java 8 revealed

  • 2. Who We are Bazlur Rahman Rokon Associate Software Engineer, Therap Services, LLC Sazzadur Rahman Software Engineer, Kona Software Lab Ltd.
  • 3. What’s new in Java 8 1. Lambda Expressions 2. Method references 3. Default methods 4. Bulk Data Operation → Stream API 5. Date-Time 6. And a lot more ……
  • 4. Assumption 1. We really love abstraction 2. We Actually Build cool Stuffs 3. We are programmers and lazy 4. We work only day time and go home early (Well, we have life, right :/ ) 5. Users want too many features 6. As we are lazy, we don’t want to do too much work. 7. So we love “Less code, do more” philosophy
  • 5. The Best Code is No Code At All 1. Code is bad 2. It rots 3. It requires periodic maintenance 4. But the fact is, we love coding, more specifically less coding
  • 6. Lambda in Action public interface Runnable { public abstract void run(); }
  • 7. Lambda in Action cont. new Thread(new Runnable() { @Override public void run() { System.out.println("JUGBD Meetup 3.0"); } }).start();
  • 8. new Thread(new Runnable() { @Override public void run() { System.out.println("JUGBD Meetup 3.0"); } }).start(); Code I’m interested in
  • 9. new Thread(new Runnable() { @Override public void run() { System.out.println("JUGBD Meetup 3.0"); } }).start(); Ceremony
  • 10. Less code ☺ new Thread(() -> System.out.println("JUGBD Meetup 3.0")) .start();
  • 11. What is Lambda Expression () -> { }
  • 12. What is Lambda Expression (Thing t ) -> { }
  • 13. What is Lambda Expression (Thing t ) -> { } (Thing t , More m) -> { }
  • 14. Let’s have a situation public class Person { private String name; private LocalDate birthday; private Sex gender; private String emailAddress; private String cellNo; // getters and setters//
  • 15. What we want to do 1. Search based on characteristics and send email/call 1. find older than 60 -> then need Elderly allowance 2. find voters 1. kids -> less than 18 -> they are not allowed to vote, so ignore them 2. sort by name, by age
  • 16. Take # 1 public void findPersonOlder(List<Person> persons) { for (Person p : persons) { if (p.getAge() > 60) { sendEmail(p.getEmailAddress()); } } }
  • 17. Take #2 public void findEligibleVoters(List<Person> persons) { for (Person p : persons) { if (p.getAge() > 18) { sendEmail(p.getEmailAddress()); } } }
  • 18. Take # 3 public void findTargetAudienceForAd(List<Person> persons) { for (Person p : persons) { if (p.getAge() > 25 && p.getGender() == Sex.MALE) { sendEmail(p.getEmailAddress()); } } }
  • 19. A lots of combinations We can keep going on and on and on….
  • 20. Lets parameterize the behavior public interface PersonPredicate { public boolean testPerson(Person p); }
  • 21. public void processPerson(List<Person> persons, PersonPredicate predicate) { for (Person p : persons) { if (predicate.testPerson(p)) { sendEmail(p.getEmailAddress()); } } }
  • 22. Revisit Take #2 processPerson(persons, new PersonPredicate() { @Override public boolean testPerson(Person p) { return p.getAge() > 18; } });
  • 23. Revisit Take #3 processPerson(persons, new PersonPredicate() { @Override public boolean testPerson(Person p) { return p.getAge() > 25 && p.getGender() == Sex.MALE; } });
  • 24. We want to call as well public interface PersonConsumer { public void accept (String phoneNumber); }
  • 25. public void processPerson(List<Person> persons, PersonPredicate predicate, PersonConsumer consumer) { for (Person p : persons) { if (predicate.testPerson(p)) { String cellNo = p.getCellNo(); consumer.accept(cellNo); } } }
  • 26. Lets put it a bit harder public void processPerson(List<Person> persons, PersonPredicate predicate, PersonConsumer consumer) { for (Person p : persons) { if (predicate.testPerson(p)) { String cellNo = p.getCellNo(); consumer.accept(cellNo); } } }
  • 27. public interface PersonMapper { public String map(Person p); }
  • 28. public void processPerson(List<Person> persons, PersonPredicate predicate, PersonMapper mapper, PersonConsumer consumer) { for (Person p : persons) { if (predicate.testPerson(p)) { String value = mapper.map(p); consumer.accept(value); }
  • 29. Good going .. processPerson(persons,new PersonPredicate() { @Override public boolean testPerson(Person p) { return p.getAge() > 18; } }, new PersonMapper() { @Override public String map(Person p) { return p.getCellNo(); } }, new PersonConsumer() { @Override public void accept(String value) { call(value); } });
  • 31. Revisit the Again processPerson(persons, new PersonPredicate() { @Override public boolean testPerson(Person p) { return p.getAge() > 18; } });
  • 32. Boilerplate code processPerson(persons, new PersonPredicate() { @Override public boolean testPerson(Person p) { return p.getAge() > 18; } });
  • 33. We are in the age of Java 8 , lets throw away boilerplate code processPerson(persons, p return p.getAge() > 18; );
  • 34. Our first lambda processPerson(persons, p -> p.getAge() > 18);
  • 35. Lets call voters processPerson(persons, p -> p.getAge() > 18, p1 -> p1.getCellNo(), c -> call(c) );
  • 36. Functional Interface @FunctionalInterface public interface PersonMapper { public String map(Person p); } public interface PersonPredicate { public boolean testPerson(Person p); } @FunctionalInterface public interface PersonMapper { public String map(Person p); }
  • 38. So we were basically doing Source -> filter -> map -> apply Lambda Lambda Lambda
  • 40. What is Stream? •A sequence of elements from a source supporting sequential and parallel aggregate operations, While completely abstracting the details of low level multi threading logic. •Sources can be Any type of Collection, Array, or any I/O operation who provides data to the Stream. •Aggregate operations are operations to collect or extract necessary information from a stream or collection.
  • 41. What is Stream? persons .stream() .filter(p-> p.getAge()>19) .map(p-> p.getCellNo()) .forEach( c-> call(c)); Intermdediate Operation Terminal Operation Get Stream Source Pipelining Intermdediate Operation
  • 43. Map and flatMap List<Integer> numbers = Arrays.asList(1, 2, 3, 4); List<List<Integer>> mapped = numbers.stream() .map(number -> Arrays.asList(number -1, number, number +1)) .collect(Collectors.toList()); System.out.println(mapped); //:> [[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5]] List<Integer> flattened = numbers.stream() .flatMap(number -> Arrays.asList(number -1, number, number +1).stream()) .collect(Collectors.toList()); System.out.println(flattened); //:> [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5]
  • 45. allMatch and noneMatch //Check if All of the students have distinction Boolean hasAllStudentsWithDistinction = students.stream() .allMatch(student -> student.getScore() > 80); //Return true if None of the students are over distinction Boolean hasAllStudentsBelowDistinction = students.stream() .noneMatch(student -> student.getScore() > 80);
  • 46. Reduce Reduces the whole stream into a single value //Summing all elements of a stream Integer sum = numbers.stream() .reduce(0, (x, y) -> x + y); //reduce(identity, accumulator) Integer min = numbers.stream() .reduce(0, Integer::min);
  • 47. What about having no terminal Operation? persons .stream() .filter(p-> p.getAge()>19) .map(p-> p.getCellNo()) Intermdediate Operation Get Stream Source Pipelining Intermdediate Operation
  • 48. Lazy and Eager Did you scrolled your facebook timeline, down to the beginning?
  • 49. Laziness of Stream operations • Current era is of Big Data, Parallel Processing and being real time. • When dealing with Big Data Laziness is a big deal. • Stream API is inherently Lazy and based on “Process on Demand” behavior.
  • 50. Laziness of Stream operations Stream<String> streamOfNames = students.stream() .map(student -> { System.out.println("In Map - " + student.getName()); return student.getName(); }); //Just to add some delay for (int i = 1; i <= 5; i++) { Thread.sleep(1000); System.out.println(i + " sec"); } //Called a terminal operation on the stream streamOfNames.collect(Collectors.toList()); Output: 1 sec 2 sec 3 sec 4 sec 5 sec In Map - Tom In Map - Chris In Map - Dave
  • 51. Short Circuit //List of first 3 students who have age > 20 students.stream() .filter(s -> s.getAge() > 20) .map(Student::getName) .limit(3) .collect(Collectors.toList());