SlideShare a Scribd company logo
LAMBDA EXPRESSIONS
JAVA 8
INTERFACES IN JAVA 8
• In JAVA 8, the interface body can contain
• Abstract methods
• Static methods
• Default methods
• Example
public interface SampleIface {
public void process();
public static void print(){
System.out.println("Static Method In Interface");
}
public default void apply(){
System.out.println("Default Metod In Interface");
}
}
FUNCTIONAL INTERFACE
• java.lang.Runnable, java.awt.event.ActionListener,
java.util.Comparator, java.util.concurrent.Callable … etc ;
• There is some common feature among the stated interfaces and that
feature is they have only one method declared in their interface definition
• These interfaces are called Single Abstract Method interfaces (SAM
Interfaces)
• With Java 8 the same concept of SAM interfaces is recreated and are called
Functional interfaces
• There’s an annotation introduced- @FunctionalInterface which can be
used for compiler level errors when the interface you have annotated is not
a valid Functional Interface.
EXAMPLE
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
default Predicate<T> and(Predicate<? super T> other) {
------SOME CODE--------
}
default Predicate<T> negate() {
------SOME CODE--------
}
default Predicate<T> or(Predicate<? super T> other) {
------SOME CODE--------
}
static <T> Predicate<T> isEqual(Object targetRef) {
------SOME CODE--------
}
}
ANONYMOUS INNER CLASSES
• An interface that contains only one method, then the syntax of anonymous classes
may seem unwieldy and unclear.
• We're usually trying to pass functionality as an argument to another method, such as
what action should be taken when someone clicks a button.
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK Button Clicked");
}
});
LAMBDA
• Lambda expressions enable us to treat functionality as method argument, or
code as data
• Lambda expressions let us express instances of single-method classes more
compactly.
• A lambda expression is composed of three parts.
Argument List Arrow Token Body
(int x, int y) -> x + y
okButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("OK Button Clicked");
}
});
okButton.addActionListener((ActionEvent e) -> {
System.out.println("OK Button Clicked - 2");
});
okButton.addActionListener(
(ActionEvent e) -> System.out.println("OK Button Clicked"));
okButton.addActionListener(e -> System.out.println("OK Button Clicked"));
Equivalent Lambda expression
EXAMPLE
EXAMPLE
new Thread(new Runnable() {
@Override
public void run() {
for (int i=1;i<=10;i++){
System.out.println("i = " + i);
}
}
}).start();
Equivalent Lambda expression
new Thread(() -> {
for (int i=1;i<=10;i++){
System.out.println("i = " + i);
}
}).start();
EXAMPLE
Collections.sort(employeeList, new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return e1.getEmpName().compareTo(e2.getEmpName());
}
});
Equivalent Lambda expression
Collections.sort(employeeList,
(e1, e2) -> e1.getEmpName().compareTo(e2.getEmpName()));
EXAMPLE
Collections.sort(employeeList,
(e1, e2) -> e1.getEmpName().compareTo(e2.getEmpName()));
Collections.sort(employeeList,
(Employee e1, Employee e2) -> e1.getEmpName().compareTo(e2.getEmpName()));
Collections.sort(employeeList, (e1, e2) -> {
return e1.getEmpName().compareTo(e2.getEmpName());
});
Collections.sort(employeeList, (Employee e1, Employee e2) -> {
return e1.getEmpName().compareTo(e2.getEmpName());
});
METHOD REFERENCES
• Sometimes a lambda expression does nothing but call an existing method
• In those cases, it's often clearer to refer to the existing method by name
• Method references enable you to do this; they are compact, easy-to-read
lambda expressions for methods that already have a name.
• Different kinds of method references:
Kind Example
Reference to a static method ContainingClass::staticMethodName
Reference to an instance method of a particular object containingObject::instanceMethodName
Reference to a constructor ClassName::new
REFERENCE TO A STATIC METHOD
public class Person {
private String firstName;
private String lastName;
private Calendar birthday;
//GETTERS & SETTERS
public static int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
Collections.sort(personList, (p1,p2) -> Person.compareByAge(p1, p2));
Lambda expression
Equivalent Method Reference
Collections.sort(personList, Person::compareByAge);
REFERENCE TO AN INSTANCE METHOD
public class ComparisonProvider {
public int compareByName(Person a, Person b) {
return a.getFirstName().compareTo(b.getFirstName());
}
public int compareByAge(Person a, Person b) {
return a.getBirthday().compareTo(b.getBirthday());
}
}
ComparisonProvider comparisonProvider = new ComparisonProvider();
Collections.sort(personList, (p1,p2) -> comparisonProvider.compareByName(p1, p2));
Lambda expression
Collections.sort(personList, comparisonProvider::compareByName);
Equivalent Method Reference
REFERENCE TO A CONSTRUCTOR
public static void transfer(Map<String, String> source,
Supplier<Map<String, String>> mapSupplier){
// code to transfer
}
Anonymous Inner Class
transfer(src, new Supplier<Map<String, String>>() {
@Override
public Map<String, String> get() {
return new HashMap<>();
}
});
Lambda expression
transfer(src, () -> new HashMap<>());
Equivalent Method Reference
transfer(src, HashMap::new);
AGGREGATE OPERATIONS IN
COLLECTIONS
• Streams
• A stream is a sequence of elements. Unlike a collection, it is not a data structure
that stores elements.
• Pipelines
• A pipeline is a sequence of aggregate operations.
• PIPELINE contains the following
• A Source
• Zero or more intermediate operations
• A terminal operation
EXAMPLE
List<Employee> employeeList = new ArrayList<>();
//Add elements into employee list.
employeeList
.stream()
.filter(employee -> employee.getGender() == Person.Sex.FEMALE)
.forEach(employee -> System.out.println(employee));
int totalAge = employeeList
.stream()
.mapToInt(Person::getAge)
.sum();
double average = employeeList
.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.mapToInt(Person::getAge)
.average()
.getAsDouble();
Java 8 Lambda Expressions

More Related Content

What's hot

Java8
Java8Java8
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
Manav Prasad
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
Sergii Stets
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
Andrzej Grzesik
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
Sanjoy Kumar Roy
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
Jim Bethancourt
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
Rohit Verma
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
icarter09
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
Rahman USTA
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
Ganesh Samarthyam
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
Tobias Coetzee
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
GlobalLogic Ukraine
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
NexThoughts Technologies
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
Ganesh Samarthyam
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
Naveen Hegde
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
Martin Toshev
 
Lambdas HOL
Lambdas HOLLambdas HOL
Lambdas HOL
Oleg Tsal-Tsalko
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
Aniket Thakur
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
Knoldus Inc.
 
Scala test
Scala testScala test

What's hot (20)

Java8
Java8Java8
Java8
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Java 8: the good parts!
Java 8: the good parts!Java 8: the good parts!
Java 8: the good parts!
 
Major Java 8 features
Major Java 8 featuresMajor Java 8 features
Major Java 8 features
 
Java 8 Feature Preview
Java 8 Feature PreviewJava 8 Feature Preview
Java 8 Feature Preview
 
java 8 new features
java 8 new features java 8 new features
java 8 new features
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Java 8 - Project Lambda
Java 8 - Project LambdaJava 8 - Project Lambda
Java 8 - Project Lambda
 
Functional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting LambdasFunctional Programming in Java 8 - Exploiting Lambdas
Functional Programming in Java 8 - Exploiting Lambdas
 
Streams in Java 8
Streams in Java 8Streams in Java 8
Streams in Java 8
 
Java 8 Intro - Core Features
Java 8 Intro - Core FeaturesJava 8 Intro - Core Features
Java 8 Intro - Core Features
 
Actors model in gpars
Actors model in gparsActors model in gpars
Actors model in gpars
 
Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8Functional Thinking - Programming with Lambdas in Java 8
Functional Thinking - Programming with Lambdas in Java 8
 
Java SE 8 - New Features
Java SE 8 - New FeaturesJava SE 8 - New Features
Java SE 8 - New Features
 
New Features in JDK 8
New Features in JDK 8New Features in JDK 8
New Features in JDK 8
 
Lambdas HOL
Lambdas HOLLambdas HOL
Lambdas HOL
 
Java 8 new features
Java 8 new featuresJava 8 new features
Java 8 new features
 
Introduction to Java 8
Introduction to Java 8Introduction to Java 8
Introduction to Java 8
 
Scala test
Scala testScala test
Scala test
 

Similar to Java 8 Lambda Expressions

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
BruceLee275640
 
Java 8
Java 8Java 8
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
Ganesh Samarthyam
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
Mario Fusco
 
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
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
Ganesh Samarthyam
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
Yuriy Bondaruk
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
Sergii Maliarov
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
Tomasz Kowalczewski
 
Java 8
Java 8Java 8
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
Andrea Iacono
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java SE 8
Java SE 8Java SE 8
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
chetanpatilcp783
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
Maýur Chourasiya
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
Dian Aditya
 

Similar to Java 8 Lambda Expressions (20)

java150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptxjava150929145120-lva1-app6892 (2).pptx
java150929145120-lva1-app6892 (2).pptx
 
Java 8
Java 8Java 8
Java 8
 
Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
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
 
Java8.part2
Java8.part2Java8.part2
Java8.part2
 
Lambda Functions in Java 8
Lambda Functions in Java 8Lambda Functions in Java 8
Lambda Functions in Java 8
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Java8: what's new and what's hot
Java8: what's new and what's hotJava8: what's new and what's hot
Java8: what's new and what's hot
 
Java gets a closure
Java gets a closureJava gets a closure
Java gets a closure
 
Java 8
Java 8Java 8
Java 8
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Functional Java 8 in everyday life
Functional Java 8 in everyday lifeFunctional Java 8 in everyday life
Functional Java 8 in everyday life
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Java SE 8
Java SE 8Java SE 8
Java SE 8
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
What's new in java 8
What's new in java 8What's new in java 8
What's new in java 8
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 

More from Hyderabad Scalability Meetup

Serverless architectures
Serverless architecturesServerless architectures
Serverless architectures
Hyderabad Scalability Meetup
 
GeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming LanguagesGeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming Languages
Hyderabad Scalability Meetup
 
Geeknight : Artificial Intelligence and Machine Learning
Geeknight : Artificial Intelligence and Machine LearningGeeknight : Artificial Intelligence and Machine Learning
Geeknight : Artificial Intelligence and Machine Learning
Hyderabad Scalability Meetup
 
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
Map reduce and the art of Thinking Parallel   - Dr. Shailesh KumarMap reduce and the art of Thinking Parallel   - Dr. Shailesh Kumar
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
Hyderabad Scalability Meetup
 
Offline first geeknight
Offline first geeknightOffline first geeknight
Offline first geeknight
Hyderabad Scalability Meetup
 
Understanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLUnderstanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQL
Hyderabad Scalability Meetup
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
Hyderabad Scalability Meetup
 
Nlp
NlpNlp
Internet of Things - GeekNight - Hyderabad
Internet of Things - GeekNight - HyderabadInternet of Things - GeekNight - Hyderabad
Internet of Things - GeekNight - Hyderabad
Hyderabad Scalability Meetup
 
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep DiveDemystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Hyderabad Scalability Meetup
 
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep DiveDemystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Hyderabad Scalability Meetup
 
No SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability MeetupNo SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability Meetup
Hyderabad Scalability Meetup
 
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability MeetupApache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Hyderabad Scalability Meetup
 
Docker by demo
Docker by demoDocker by demo

More from Hyderabad Scalability Meetup (15)

Serverless architectures
Serverless architecturesServerless architectures
Serverless architectures
 
GeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming LanguagesGeekNight: Evolution of Programming Languages
GeekNight: Evolution of Programming Languages
 
Geeknight : Artificial Intelligence and Machine Learning
Geeknight : Artificial Intelligence and Machine LearningGeeknight : Artificial Intelligence and Machine Learning
Geeknight : Artificial Intelligence and Machine Learning
 
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
Map reduce and the art of Thinking Parallel   - Dr. Shailesh KumarMap reduce and the art of Thinking Parallel   - Dr. Shailesh Kumar
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
 
Offline first geeknight
Offline first geeknightOffline first geeknight
Offline first geeknight
 
Understanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQLUnderstanding and building big data Architectures - NoSQL
Understanding and building big data Architectures - NoSQL
 
Turbo charging v8 engine
Turbo charging v8 engineTurbo charging v8 engine
Turbo charging v8 engine
 
Git internals
Git internalsGit internals
Git internals
 
Nlp
NlpNlp
Nlp
 
Internet of Things - GeekNight - Hyderabad
Internet of Things - GeekNight - HyderabadInternet of Things - GeekNight - Hyderabad
Internet of Things - GeekNight - Hyderabad
 
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep DiveDemystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep Dive
 
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep DiveDemystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep Dive
 
No SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability MeetupNo SQL and MongoDB - Hyderabad Scalability Meetup
No SQL and MongoDB - Hyderabad Scalability Meetup
 
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability MeetupApache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
 
Docker by demo
Docker by demoDocker by demo
Docker by demo
 

Recently uploaded

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 

Recently uploaded (20)

State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...How world-class product teams are winning in the AI era by CEO and Founder, P...
How world-class product teams are winning in the AI era by CEO and Founder, P...
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 

Java 8 Lambda Expressions

  • 2. INTERFACES IN JAVA 8 • In JAVA 8, the interface body can contain • Abstract methods • Static methods • Default methods • Example public interface SampleIface { public void process(); public static void print(){ System.out.println("Static Method In Interface"); } public default void apply(){ System.out.println("Default Metod In Interface"); } }
  • 3. FUNCTIONAL INTERFACE • java.lang.Runnable, java.awt.event.ActionListener, java.util.Comparator, java.util.concurrent.Callable … etc ; • There is some common feature among the stated interfaces and that feature is they have only one method declared in their interface definition • These interfaces are called Single Abstract Method interfaces (SAM Interfaces) • With Java 8 the same concept of SAM interfaces is recreated and are called Functional interfaces • There’s an annotation introduced- @FunctionalInterface which can be used for compiler level errors when the interface you have annotated is not a valid Functional Interface.
  • 4. EXAMPLE @FunctionalInterface public interface Predicate<T> { boolean test(T t); default Predicate<T> and(Predicate<? super T> other) { ------SOME CODE-------- } default Predicate<T> negate() { ------SOME CODE-------- } default Predicate<T> or(Predicate<? super T> other) { ------SOME CODE-------- } static <T> Predicate<T> isEqual(Object targetRef) { ------SOME CODE-------- } }
  • 5. ANONYMOUS INNER CLASSES • An interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. • We're usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("OK Button Clicked"); } });
  • 6. LAMBDA • Lambda expressions enable us to treat functionality as method argument, or code as data • Lambda expressions let us express instances of single-method classes more compactly. • A lambda expression is composed of three parts. Argument List Arrow Token Body (int x, int y) -> x + y
  • 7. okButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println("OK Button Clicked"); } }); okButton.addActionListener((ActionEvent e) -> { System.out.println("OK Button Clicked - 2"); }); okButton.addActionListener( (ActionEvent e) -> System.out.println("OK Button Clicked")); okButton.addActionListener(e -> System.out.println("OK Button Clicked")); Equivalent Lambda expression EXAMPLE
  • 8. EXAMPLE new Thread(new Runnable() { @Override public void run() { for (int i=1;i<=10;i++){ System.out.println("i = " + i); } } }).start(); Equivalent Lambda expression new Thread(() -> { for (int i=1;i<=10;i++){ System.out.println("i = " + i); } }).start();
  • 9. EXAMPLE Collections.sort(employeeList, new Comparator<Employee>() { @Override public int compare(Employee e1, Employee e2) { return e1.getEmpName().compareTo(e2.getEmpName()); } }); Equivalent Lambda expression Collections.sort(employeeList, (e1, e2) -> e1.getEmpName().compareTo(e2.getEmpName()));
  • 10. EXAMPLE Collections.sort(employeeList, (e1, e2) -> e1.getEmpName().compareTo(e2.getEmpName())); Collections.sort(employeeList, (Employee e1, Employee e2) -> e1.getEmpName().compareTo(e2.getEmpName())); Collections.sort(employeeList, (e1, e2) -> { return e1.getEmpName().compareTo(e2.getEmpName()); }); Collections.sort(employeeList, (Employee e1, Employee e2) -> { return e1.getEmpName().compareTo(e2.getEmpName()); });
  • 11. METHOD REFERENCES • Sometimes a lambda expression does nothing but call an existing method • In those cases, it's often clearer to refer to the existing method by name • Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name. • Different kinds of method references: Kind Example Reference to a static method ContainingClass::staticMethodName Reference to an instance method of a particular object containingObject::instanceMethodName Reference to a constructor ClassName::new
  • 12. REFERENCE TO A STATIC METHOD public class Person { private String firstName; private String lastName; private Calendar birthday; //GETTERS & SETTERS public static int compareByAge(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } } Collections.sort(personList, (p1,p2) -> Person.compareByAge(p1, p2)); Lambda expression Equivalent Method Reference Collections.sort(personList, Person::compareByAge);
  • 13. REFERENCE TO AN INSTANCE METHOD public class ComparisonProvider { public int compareByName(Person a, Person b) { return a.getFirstName().compareTo(b.getFirstName()); } public int compareByAge(Person a, Person b) { return a.getBirthday().compareTo(b.getBirthday()); } } ComparisonProvider comparisonProvider = new ComparisonProvider(); Collections.sort(personList, (p1,p2) -> comparisonProvider.compareByName(p1, p2)); Lambda expression Collections.sort(personList, comparisonProvider::compareByName); Equivalent Method Reference
  • 14. REFERENCE TO A CONSTRUCTOR public static void transfer(Map<String, String> source, Supplier<Map<String, String>> mapSupplier){ // code to transfer } Anonymous Inner Class transfer(src, new Supplier<Map<String, String>>() { @Override public Map<String, String> get() { return new HashMap<>(); } }); Lambda expression transfer(src, () -> new HashMap<>()); Equivalent Method Reference transfer(src, HashMap::new);
  • 15. AGGREGATE OPERATIONS IN COLLECTIONS • Streams • A stream is a sequence of elements. Unlike a collection, it is not a data structure that stores elements. • Pipelines • A pipeline is a sequence of aggregate operations. • PIPELINE contains the following • A Source • Zero or more intermediate operations • A terminal operation
  • 16. EXAMPLE List<Employee> employeeList = new ArrayList<>(); //Add elements into employee list. employeeList .stream() .filter(employee -> employee.getGender() == Person.Sex.FEMALE) .forEach(employee -> System.out.println(employee)); int totalAge = employeeList .stream() .mapToInt(Person::getAge) .sum(); double average = employeeList .stream() .filter(p -> p.getGender() == Person.Sex.MALE) .mapToInt(Person::getAge) .average() .getAsDouble();