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

PDF
Lambda Expressions in Java
PDF
Programming with Lambda Expressions in Java
PPTX
Java 8 lambda
PDF
Java 8 Lambda Expressions & Streams
PPTX
Java 8 Lambda and Streams
PPTX
Java 8 presentation
PDF
Java8 features
PDF
Java 8 features
Lambda Expressions in Java
Programming with Lambda Expressions in Java
Java 8 lambda
Java 8 Lambda Expressions & Streams
Java 8 Lambda and Streams
Java 8 presentation
Java8 features
Java 8 features

What's hot (20)

PDF
PPTX
Java 8 streams
PPTX
Java 8 - Features Overview
PDF
Java 8: the good parts!
PPT
Major Java 8 features
PPTX
Java 8 Feature Preview
PPTX
java 8 new features
PPTX
Lambda Expressions in Java 8
PDF
Java 8 - Project Lambda
PDF
Functional Programming in Java 8 - Exploiting Lambdas
PDF
Streams in Java 8
PPTX
Java 8 Intro - Core Features
PPTX
Actors model in gpars
PDF
Functional Thinking - Programming with Lambdas in Java 8
PPTX
Java SE 8 - New Features
PPTX
New Features in JDK 8
PDF
Lambdas HOL
PPTX
Java 8 new features
ODP
Introduction to Java 8
PDF
Java 8 streams
Java 8 - Features Overview
Java 8: the good parts!
Major Java 8 features
Java 8 Feature Preview
java 8 new features
Lambda Expressions in Java 8
Java 8 - Project Lambda
Functional Programming in Java 8 - Exploiting Lambdas
Streams in Java 8
Java 8 Intro - Core Features
Actors model in gpars
Functional Thinking - Programming with Lambdas in Java 8
Java SE 8 - New Features
New Features in JDK 8
Lambdas HOL
Java 8 new features
Introduction to Java 8
Ad

Similar to Java 8 Lambda Expressions (20)

PPTX
java150929145120-lva1-app6892 (2).pptx
PDF
PDF
Java 8 Lambda Built-in Functional Interfaces
PPTX
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
PDF
Java 8 Workshop
PDF
Java 8 new features or the ones you might actually use
PDF
Unit-3.pptx.pdf java api knowledge apiii
PPTX
Java8.part2
PDF
Lambda Functions in Java 8
PDF
Java8: Language Enhancements
PPTX
Java8: what's new and what's hot
PPTX
Java gets a closure
PDF
PDF
FP in Java - Project Lambda and beyond
PDF
Functional Java 8 in everyday life
PDF
Java Collections Tutorials
PPTX
PPTX
Chap-2 Classes & Methods.pptx
PPTX
Java 8 features
PDF
What's new in java 8
java150929145120-lva1-app6892 (2).pptx
Java 8 Lambda Built-in Functional Interfaces
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
Java 8 Workshop
Java 8 new features or the ones you might actually use
Unit-3.pptx.pdf java api knowledge apiii
Java8.part2
Lambda Functions in Java 8
Java8: Language Enhancements
Java8: what's new and what's hot
Java gets a closure
FP in Java - Project Lambda and beyond
Functional Java 8 in everyday life
Java Collections Tutorials
Chap-2 Classes & Methods.pptx
Java 8 features
What's new in java 8
Ad

More from Hyderabad Scalability Meetup (15)

PDF
Serverless architectures
PDF
GeekNight: Evolution of Programming Languages
PPTX
Geeknight : Artificial Intelligence and Machine Learning
PDF
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
PDF
Offline first geeknight
PDF
Understanding and building big data Architectures - NoSQL
PPTX
Turbo charging v8 engine
PPTX
Internet of Things - GeekNight - Hyderabad
PDF
Demystify Big Data, Data Science & Signal Extraction Deep Dive
PDF
Demystify Big Data, Data Science & Signal Extraction Deep Dive
PPT
No SQL and MongoDB - Hyderabad Scalability Meetup
PPTX
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup
PPT
Serverless architectures
GeekNight: Evolution of Programming Languages
Geeknight : Artificial Intelligence and Machine Learning
Map reduce and the art of Thinking Parallel - Dr. Shailesh Kumar
Offline first geeknight
Understanding and building big data Architectures - NoSQL
Turbo charging v8 engine
Internet of Things - GeekNight - Hyderabad
Demystify Big Data, Data Science & Signal Extraction Deep Dive
Demystify Big Data, Data Science & Signal Extraction Deep Dive
No SQL and MongoDB - Hyderabad Scalability Meetup
Apache Spark - Lightning Fast Cluster Computing - Hyderabad Scalability Meetup

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
Big Data Technologies - Introduction.pptx
PDF
Machine learning based COVID-19 study performance prediction
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PPT
Teaching material agriculture food technology
PPTX
Cloud computing and distributed systems.
PPTX
MYSQL Presentation for SQL database connectivity
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Advanced IT Governance
PDF
Approach and Philosophy of On baking technology
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Spectral efficient network and resource selection model in 5G networks
Big Data Technologies - Introduction.pptx
Machine learning based COVID-19 study performance prediction
Unlocking AI with Model Context Protocol (MCP)
NewMind AI Weekly Chronicles - August'25 Week I
Teaching material agriculture food technology
Cloud computing and distributed systems.
MYSQL Presentation for SQL database connectivity
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Advanced IT Governance
Approach and Philosophy of On baking technology
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Advanced methodologies resolving dimensionality complications for autism neur...
The AUB Centre for AI in Media Proposal.docx
NewMind AI Monthly Chronicles - July 2025
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows

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();