JAVA 8: LAMBDA BUILT-IN
FUNCTIONAL INTERFACES
ganesh samarthyam
ganesh.samarthyam@gmail.com
Functional interfaces
@FunctionalInterface
interface LambdaFunction {
void call();
}
Functional interface
Abstract method providing the signature of the
lambda function
Annotation to explicitly state that it is a functional
interface
Java 8 lambdas - “Hello world!”
@FunctionalInterface
interface LambdaFunction {
void call();
}
class FirstLambda {
public static void main(String []args) {
LambdaFunction lambdaFunction = () -> System.out.println("Hello world");
lambdaFunction.call();
}
}
Functional interface - provides
signature for lambda functions
Lambda function/expression
Call to the lambda
Prints “Hello world” on the console when executed
Older Single Abstract Methods (SAMs)
// in java.lang package
interface Runnable { void run(); }
// in java.util package
interface Comparator<T> { boolean compare(T x, T y); }
// java.awt.event package:
interface ActionListener { void actionPerformed(ActionEvent e) }
// java.io package
interface FileFilter { boolean accept(File pathName); }
Functional interfaces: Single abstract methods
@FunctionalInterface
interface LambdaFunction {
void call();
// Single Abstract Method (SAM)
}
Using built-in functional interfaces
// within Iterable interface
default void forEach(Consumer<? super T> action) {
Objects.requireNonNull(action);
for (T t : this) {
action.accept(t);
}
}
// in java.util.function package
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
// the default andThen method elided
}
Using built-in functional interfaces
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
Consumer<String> printString = string -> System.out.println(string);
strings.forEach(printString);
List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo");
strings.forEach(string -> System.out.println(string));
Built-in functional interfaces
Built-in functional interfaces are a
part of the java.util.function
package (in Java 8)
Built-in interfaces
Predicate<T> Checks a condition and returns a
boolean value as result
In filter() method in
java.util.stream.Stream
which is used to remove elements
in the stream that don’t match the
given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but
returns nothing
In forEach() method in
collections and in
java.util.stream.Stream; this
method is used for traversing all
the elements in the collection orFunction<T,
R>
Functions that take an argument and
return a result
In map() method in
java.util.stream.Stream to
transform or operate on the passed
value and return a result.
Supplier<T> Operation that returns a value to the
caller (the returned value could be
same or different values)
In generate() method in
java.util.stream.Stream to
create a infinite stream of
elements.
Predicate interface
Stream.of("hello", "world")
.filter(str -> str.startsWith("h"))
.forEach(System.out::println);
The filter() method takes a Predicate
as an argument (predicates are
functions that check a condition and
return a boolean value)
Predicate interface
Predicate interface
A Predicate<T> “affirms” something as true or
false: it takes an argument of type T, and returns a
boolean value. You can call test() method on a
Predicate object.
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
// other methods elided
}
Predicate interface: Example
import java.util.function.Predicate;
public class PredicateTest {
public static void main(String []args) {
Predicate<String> nullCheck = arg -> arg != null;
Predicate<String> emptyCheck = arg -> arg.length() > 0;
Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck);
String helloStr = "hello";
System.out.println(nullAndEmptyCheck.test(helloStr));
String nullStr = null;
System.out.println(nullAndEmptyCheck.test(nullStr));
}
}
Prints:
true
false
Predicate interface: Example
import java.util.List;
import java.util.ArrayList;
public class RemoveIfMethod {
public static void main(String []args) {
List<String> greeting = new ArrayList<>();
greeting.add("hello");
greeting.add("world");
greeting.removeIf(str -> !str.startsWith("h"));
greeting.forEach(System.out::println);
}
}
Prints:
hello
Consumer interface
Stream.of("hello", "world")
.forEach(System.out::println);
// void forEach(Consumer<? super T> action);
Prints:
hello
world
Consumer interface
Consumer interface
A Consumer<T> “consumes” something: it takes
an argument (of generic type T) and returns
nothing (void). You can call accept() method on a
Consumer object.
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
// the default andThen method elided
}
Consumer interface: Example
Consumer<String> printUpperCase =
str -> System.out.println(str.toUpperCase());
printUpperCase.accept("hello");
Prints:
HELLO
Consumer interface: Example
import java.util.stream.Stream;
import java.util.function.Consumer;
class ConsumerUse {
public static void main(String []args) {
Stream<String> strings = Stream.of("hello", "world");
Consumer<String> printString = System.out::println;
strings.forEach(printString);
}
}
Prints:
hello
world
Function interface
import java.util.Arrays;
public class FunctionUse {
public static void main(String []args) {
Arrays.stream("4, -9, 16".split(", "))
.map(Integer::parseInt)
.map(i -> (i < 0) ? -i : i)
.forEach(System.out::println);
}
}
Prints:
4
9
16
Function interface
Function interface
A Function<T, R> “operates” on something and
returns something: it takes one argument (of
generic type T) and returns an object (of generic
type R). You can call apply() method on a Function
object.
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
// other methods elided
}
Function interface: Example
Function<String, Integer> strLength = str -> str.length();
System.out.println(strLength.apply("supercalifragilisticexpialidocious"));
Prints:
34
Function interface: Example
import java.util.Arrays;
import java.util.function.Function;
public class CombineFunctions {
public static void main(String []args) {
Function<String, Integer> parseInt = Integer:: parseInt ;
Function<Integer, Integer> absInt = Math:: abs ;
Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt)
Arrays.stream("4, -9, 16".split(", "))
.map(parseAndAbsInt)
.forEach(System. out ::println);
}
}
Prints:
4
9
16
Supplier interface
import java.util.stream.Stream;
import java.util.Random;
class GenerateBooleans {
public static void main(String []args) {
Random random = new Random();
Stream.generate(random::nextBoolean)
.limit(2)
.forEach(System.out::println);
}
}
Prints two boolean
values “true” and “false”
in random order
Supplier interface
Supplier interface
A Supplier<T> “supplies” takes nothing but
returns something: it has no arguments and
returns an object (of generic type T). You can call
get() method on a Supplier object
@FunctionalInterface
public interface Supplier<T> {
T get();
// no other methods in this interface
}
Supplier interface: Example
Supplier<String> currentDateTime = () -> LocalDateTime.now().toString();
System.out.println(currentDateTime.get());
Prints current time:
2015-10-16T12:40:55.164
Summary of built-in interfaces in
java.util.function interface
❖ There are only four core functional interfaces in this
package: Predicate, Consumer, Function, and Supplier.
❖ The rest of the interfaces are primitive versions, binary
versions, and derived interfaces such as
UnaryOperator interface.
❖ These interfaces differ mainly on the signature of the
abstract methods they declare.
❖ You need to choose the suitable functional interface
based on the context and your need.
Check out our book!
❖ “Oracle Certified Professional Java
SE 8 Programmer Exam
1Z0-809”, S.G. Ganesh, Hari
Kiran Kumar, Tushar Sharma,
Apress, 2016.
❖ Website: ocpjava.wordpress.com
❖ Amazon: http://amzn.com/
1484218353
email sgganesh@gmail.com
website ocpjava.wordpress.com
twitter @GSamarthyam
linkedin bit.ly/sgganesh
slideshare slideshare.net/sgganesh

More Related Content

PDF
Java 8 Lambda Expressions
PPT
Collection Framework in java
PPTX
Java 8 lambda
PDF
Java8 features
ODP
Introduction to Java 8
PPTX
Java - Collections framework
PPT
Exception Handling in JAVA
PDF
Java 8 features
Java 8 Lambda Expressions
Collection Framework in java
Java 8 lambda
Java8 features
Introduction to Java 8
Java - Collections framework
Exception Handling in JAVA
Java 8 features

What's hot (20)

PPTX
java 8 new features
PPTX
Optional in Java 8
PPTX
Introduction to java 8 stream api
PDF
Methods in Java
PPT
Major Java 8 features
PPT
Core java concepts
PDF
Introduction to Java 11
PPTX
Java 8 - Features Overview
PDF
Java I/o streams
PPS
Wrapper class
PDF
Java 8 Lambda Expressions & Streams
PPTX
Multithreading in java
PPTX
Java awt (abstract window toolkit)
PPTX
Interfaces in java
PPTX
Exception handling
PPTX
Java 8 presentation
PPTX
Interface in java
PPS
Introduction to class in java
PPTX
Basic Concepts of OOPs (Object Oriented Programming in Java)
PPTX
Java 8 Lambda and Streams
java 8 new features
Optional in Java 8
Introduction to java 8 stream api
Methods in Java
Major Java 8 features
Core java concepts
Introduction to Java 11
Java 8 - Features Overview
Java I/o streams
Wrapper class
Java 8 Lambda Expressions & Streams
Multithreading in java
Java awt (abstract window toolkit)
Interfaces in java
Exception handling
Java 8 presentation
Interface in java
Introduction to class in java
Basic Concepts of OOPs (Object Oriented Programming in Java)
Java 8 Lambda and Streams
Ad

Viewers also liked (10)

PDF
Functional Java 8 in everyday life
PPTX
Java8 javatime-api
ODP
Java8
PDF
Streams in Java 8
PDF
Java 8 Date and Time API
PPTX
Eclipse Day India 2015 - Java 8 Overview
PDF
PPTX
Understanding java streams
PDF
Java 8-streams-collectors-patterns
PPT
Java tutorial PPT
Functional Java 8 in everyday life
Java8 javatime-api
Java8
Streams in Java 8
Java 8 Date and Time API
Eclipse Day India 2015 - Java 8 Overview
Understanding java streams
Java 8-streams-collectors-patterns
Java tutorial PPT
Ad

Similar to Java 8 Lambda Built-in Functional Interfaces (20)

PDF
Java 8 by example!
PDF
Lambda Functions in Java 8
PDF
Java 8 Workshop
PPTX
Java 8 Intro - Core Features
PDF
FP in Java - Project Lambda and beyond
PDF
Productive Programming in Java 8 - with Lambdas and Streams
PPTX
Java 8 new features
PDF
Wien15 java8
PDF
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
PDF
PPTX
Java 8 Feature Preview
PPTX
Java 8 features
ODP
Lambda Chops - Recipes for Simpler, More Expressive Code
PPTX
Java 8 Lambda Expressions
PDF
Java 8 new features or the ones you might actually use
PPTX
java150929145120-lva1-app6892 (2).pptx
PDF
Scala is java8.next()
PPTX
Lambdas and Laughs
PPTX
Java gets a closure
PDF
JAVA UNIT-3 ONE SHOT NOTES_64415856_2025_07_12_10__250712_103718.pdf
Java 8 by example!
Lambda Functions in Java 8
Java 8 Workshop
Java 8 Intro - Core Features
FP in Java - Project Lambda and beyond
Productive Programming in Java 8 - with Lambdas and Streams
Java 8 new features
Wien15 java8
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
Java 8 Feature Preview
Java 8 features
Lambda Chops - Recipes for Simpler, More Expressive Code
Java 8 Lambda Expressions
Java 8 new features or the ones you might actually use
java150929145120-lva1-app6892 (2).pptx
Scala is java8.next()
Lambdas and Laughs
Java gets a closure
JAVA UNIT-3 ONE SHOT NOTES_64415856_2025_07_12_10__250712_103718.pdf

More from Ganesh Samarthyam (20)

PDF
Wonders of the Sea
PDF
Animals - for kids
PDF
Applying Refactoring Tools in Practice
PDF
CFP - 1st Workshop on “AI Meets Blockchain”
PDF
Great Coding Skills Aren't Enough
PDF
College Project - Java Disassembler - Description
PDF
Coding Guidelines - Crafting Clean Code
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
PDF
Bangalore Container Conference 2017 - Brief Presentation
PDF
Bangalore Container Conference 2017 - Poster
PDF
Software Design in Practice (with Java examples)
PDF
OO Design and Design Patterns in C++
PDF
Bangalore Container Conference 2017 - Sponsorship Deck
PDF
Let's Go: Introduction to Google's Go Programming Language
PPT
Google's Go Programming Language - Introduction
PDF
Java Generics - Quiz Questions
PDF
Java Generics - by Example
PDF
Software Architecture - Quiz Questions
PDF
Docker by Example - Quiz
PDF
Core Java: Best practices and bytecodes quiz
Wonders of the Sea
Animals - for kids
Applying Refactoring Tools in Practice
CFP - 1st Workshop on “AI Meets Blockchain”
Great Coding Skills Aren't Enough
College Project - Java Disassembler - Description
Coding Guidelines - Crafting Clean Code
Design Patterns - Compiler Case Study - Hands-on Examples
Bangalore Container Conference 2017 - Brief Presentation
Bangalore Container Conference 2017 - Poster
Software Design in Practice (with Java examples)
OO Design and Design Patterns in C++
Bangalore Container Conference 2017 - Sponsorship Deck
Let's Go: Introduction to Google's Go Programming Language
Google's Go Programming Language - Introduction
Java Generics - Quiz Questions
Java Generics - by Example
Software Architecture - Quiz Questions
Docker by Example - Quiz
Core Java: Best practices and bytecodes quiz

Recently uploaded (20)

PPTX
Presentation - Summer Internship at Samatrix.io_template_2.pptx
PDF
OpenColorIO Virtual Town Hall - August 2025
PPTX
Lesson-3-Operation-System-Support.pptx-I
PDF
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
PDF
Canva Desktop App With Crack Free Download 2025?
PPT
introduction of sql, sql commands(DD,DML,DCL))
PDF
Software Development Company - swapdigit | Best Mobile App Development In India
PDF
How to Set Realistic Project Milestones and Deadlines
PPTX
AI Tools Revolutionizing Software Development Workflows
PPTX
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...
PPTX
SAP Business AI_L1 Overview_EXTERNAL.pptx
PDF
MaterialX Virtual Town Hall - August 2025
PPTX
Hexagone difital twin solution in the desgining
PDF
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
PPTX
Greedy best-first search algorithm always selects the path which appears best...
PPTX
Advanced Heap Dump Analysis Techniques Webinar Deck
PPTX
oracle_ebs_12.2_project_cutoveroutage.pptx
PPTX
Phoenix Marketo User Group: Building Nurtures that Work for Your Audience. An...
PDF
10 Mistakes Agile Project Managers Still Make
PDF
Coding with GPT-5- What’s New in GPT 5 That Benefits Developers.pdf
Presentation - Summer Internship at Samatrix.io_template_2.pptx
OpenColorIO Virtual Town Hall - August 2025
Lesson-3-Operation-System-Support.pptx-I
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
Canva Desktop App With Crack Free Download 2025?
introduction of sql, sql commands(DD,DML,DCL))
Software Development Company - swapdigit | Best Mobile App Development In India
How to Set Realistic Project Milestones and Deadlines
AI Tools Revolutionizing Software Development Workflows
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...
SAP Business AI_L1 Overview_EXTERNAL.pptx
MaterialX Virtual Town Hall - August 2025
Hexagone difital twin solution in the desgining
Multiverse AI Review 2025_ The Ultimate All-in-One AI Platform.pdf
Greedy best-first search algorithm always selects the path which appears best...
Advanced Heap Dump Analysis Techniques Webinar Deck
oracle_ebs_12.2_project_cutoveroutage.pptx
Phoenix Marketo User Group: Building Nurtures that Work for Your Audience. An...
10 Mistakes Agile Project Managers Still Make
Coding with GPT-5- What’s New in GPT 5 That Benefits Developers.pdf

Java 8 Lambda Built-in Functional Interfaces

  • 1. JAVA 8: LAMBDA BUILT-IN FUNCTIONAL INTERFACES ganesh samarthyam [email protected]
  • 2. Functional interfaces @FunctionalInterface interface LambdaFunction { void call(); } Functional interface Abstract method providing the signature of the lambda function Annotation to explicitly state that it is a functional interface
  • 3. Java 8 lambdas - “Hello world!” @FunctionalInterface interface LambdaFunction { void call(); } class FirstLambda { public static void main(String []args) { LambdaFunction lambdaFunction = () -> System.out.println("Hello world"); lambdaFunction.call(); } } Functional interface - provides signature for lambda functions Lambda function/expression Call to the lambda Prints “Hello world” on the console when executed
  • 4. Older Single Abstract Methods (SAMs) // in java.lang package interface Runnable { void run(); } // in java.util package interface Comparator<T> { boolean compare(T x, T y); } // java.awt.event package: interface ActionListener { void actionPerformed(ActionEvent e) } // java.io package interface FileFilter { boolean accept(File pathName); }
  • 5. Functional interfaces: Single abstract methods @FunctionalInterface interface LambdaFunction { void call(); // Single Abstract Method (SAM) }
  • 6. Using built-in functional interfaces // within Iterable interface default void forEach(Consumer<? super T> action) { Objects.requireNonNull(action); for (T t : this) { action.accept(t); } } // in java.util.function package @FunctionalInterface public interface Consumer<T> { void accept(T t); // the default andThen method elided }
  • 7. Using built-in functional interfaces List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); Consumer<String> printString = string -> System.out.println(string); strings.forEach(printString); List<String> strings = Arrays.asList("eeny", "meeny", "miny", "mo"); strings.forEach(string -> System.out.println(string));
  • 9. Built-in functional interfaces are a part of the java.util.function package (in Java 8)
  • 10. Built-in interfaces Predicate<T> Checks a condition and returns a boolean value as result In filter() method in java.util.stream.Stream which is used to remove elements in the stream that don’t match the given condition (i.e., predicate) asConsumer<T> Operation that takes an argument but returns nothing In forEach() method in collections and in java.util.stream.Stream; this method is used for traversing all the elements in the collection orFunction<T, R> Functions that take an argument and return a result In map() method in java.util.stream.Stream to transform or operate on the passed value and return a result. Supplier<T> Operation that returns a value to the caller (the returned value could be same or different values) In generate() method in java.util.stream.Stream to create a infinite stream of elements.
  • 11. Predicate interface Stream.of("hello", "world") .filter(str -> str.startsWith("h")) .forEach(System.out::println); The filter() method takes a Predicate as an argument (predicates are functions that check a condition and return a boolean value)
  • 13. Predicate interface A Predicate<T> “affirms” something as true or false: it takes an argument of type T, and returns a boolean value. You can call test() method on a Predicate object. @FunctionalInterface public interface Predicate<T> { boolean test(T t); // other methods elided }
  • 14. Predicate interface: Example import java.util.function.Predicate; public class PredicateTest { public static void main(String []args) { Predicate<String> nullCheck = arg -> arg != null; Predicate<String> emptyCheck = arg -> arg.length() > 0; Predicate<String> nullAndEmptyCheck = nullCheck.and(emptyCheck); String helloStr = "hello"; System.out.println(nullAndEmptyCheck.test(helloStr)); String nullStr = null; System.out.println(nullAndEmptyCheck.test(nullStr)); } } Prints: true false
  • 15. Predicate interface: Example import java.util.List; import java.util.ArrayList; public class RemoveIfMethod { public static void main(String []args) { List<String> greeting = new ArrayList<>(); greeting.add("hello"); greeting.add("world"); greeting.removeIf(str -> !str.startsWith("h")); greeting.forEach(System.out::println); } } Prints: hello
  • 16. Consumer interface Stream.of("hello", "world") .forEach(System.out::println); // void forEach(Consumer<? super T> action); Prints: hello world
  • 18. Consumer interface A Consumer<T> “consumes” something: it takes an argument (of generic type T) and returns nothing (void). You can call accept() method on a Consumer object. @FunctionalInterface public interface Consumer<T> { void accept(T t); // the default andThen method elided }
  • 19. Consumer interface: Example Consumer<String> printUpperCase = str -> System.out.println(str.toUpperCase()); printUpperCase.accept("hello"); Prints: HELLO
  • 20. Consumer interface: Example import java.util.stream.Stream; import java.util.function.Consumer; class ConsumerUse { public static void main(String []args) { Stream<String> strings = Stream.of("hello", "world"); Consumer<String> printString = System.out::println; strings.forEach(printString); } } Prints: hello world
  • 21. Function interface import java.util.Arrays; public class FunctionUse { public static void main(String []args) { Arrays.stream("4, -9, 16".split(", ")) .map(Integer::parseInt) .map(i -> (i < 0) ? -i : i) .forEach(System.out::println); } } Prints: 4 9 16
  • 23. Function interface A Function<T, R> “operates” on something and returns something: it takes one argument (of generic type T) and returns an object (of generic type R). You can call apply() method on a Function object. @FunctionalInterface public interface Function<T, R> { R apply(T t); // other methods elided }
  • 24. Function interface: Example Function<String, Integer> strLength = str -> str.length(); System.out.println(strLength.apply("supercalifragilisticexpialidocious")); Prints: 34
  • 25. Function interface: Example import java.util.Arrays; import java.util.function.Function; public class CombineFunctions { public static void main(String []args) { Function<String, Integer> parseInt = Integer:: parseInt ; Function<Integer, Integer> absInt = Math:: abs ; Function<String, Integer> parseAndAbsInt = parseInt.andThen(absInt) Arrays.stream("4, -9, 16".split(", ")) .map(parseAndAbsInt) .forEach(System. out ::println); } } Prints: 4 9 16
  • 26. Supplier interface import java.util.stream.Stream; import java.util.Random; class GenerateBooleans { public static void main(String []args) { Random random = new Random(); Stream.generate(random::nextBoolean) .limit(2) .forEach(System.out::println); } } Prints two boolean values “true” and “false” in random order
  • 28. Supplier interface A Supplier<T> “supplies” takes nothing but returns something: it has no arguments and returns an object (of generic type T). You can call get() method on a Supplier object @FunctionalInterface public interface Supplier<T> { T get(); // no other methods in this interface }
  • 29. Supplier interface: Example Supplier<String> currentDateTime = () -> LocalDateTime.now().toString(); System.out.println(currentDateTime.get()); Prints current time: 2015-10-16T12:40:55.164
  • 30. Summary of built-in interfaces in java.util.function interface ❖ There are only four core functional interfaces in this package: Predicate, Consumer, Function, and Supplier. ❖ The rest of the interfaces are primitive versions, binary versions, and derived interfaces such as UnaryOperator interface. ❖ These interfaces differ mainly on the signature of the abstract methods they declare. ❖ You need to choose the suitable functional interface based on the context and your need.
  • 31. Check out our book! ❖ “Oracle Certified Professional Java SE 8 Programmer Exam 1Z0-809”, S.G. Ganesh, Hari Kiran Kumar, Tushar Sharma, Apress, 2016. ❖ Website: ocpjava.wordpress.com ❖ Amazon: http://amzn.com/ 1484218353
  • 32. email [email protected] website ocpjava.wordpress.com twitter @GSamarthyam linkedin bit.ly/sgganesh slideshare slideshare.net/sgganesh