[go: up one dir, main page]

0% found this document useful (0 votes)
2 views6 pages

Chapter 11

This document discusses functional interfaces in Java, which are defined by having a single abstract method and are primarily used with lambda expressions and method references. It highlights the advantages of using functional interfaces, such as cleaner code and the elimination of unnecessary class creation, and provides examples of built-in functional interfaces from the java.util.function package. Additionally, it explains lambda expressions and method references, showcasing their syntax and practical applications in Java programming.

Uploaded by

s78093235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views6 pages

Chapter 11

This document discusses functional interfaces in Java, which are defined by having a single abstract method and are primarily used with lambda expressions and method references. It highlights the advantages of using functional interfaces, such as cleaner code and the elimination of unnecessary class creation, and provides examples of built-in functional interfaces from the java.util.function package. Additionally, it explains lambda expressions and method references, showcasing their syntax and practical applications in Java programming.

Uploaded by

s78093235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Object Oriented Programming With JAVA

Chapter-11

Func onal Interfaces in JAVA

Functional Interface
A functional interface in Java is a type of interface defined by having precisely
one abstract method. These interfaces are predominantly utilized with Lambda
Expressions and Method References, features introduced in Java 8. Functional
interfaces offer several advantages that can enhance your Java programming skills. A
functional interface can have default or static methods without affecting its
functional nature. By implementing functional interfaces, you can:

1. Write Cleaner and Shorter Code with Lambdas: Leveraging lambda


expressions allows you to streamline your code, making it more concise and easier to
read.
2. Utilize Functional Programming Concepts: Incorporate functional
programming principles to improve code efficiency and innovation, aligning with
modern programming trends.
3. Eliminate Unnecessary Class Creation: Simplify tasks such as actions,
filters, or event handling without the need for additional classes, reducing code
complexity and improving performance.

Syntax:
@FunctionalInterface // Optional but recommended
interface FunctionalInterfaceExample {
void display(); // Only ONE abstract method allowed
}
Key Features and Benefits
Here are the key features that define a functional interface:
a) Single Abstract Method: A functional interface contains exactly one abstract
method.
b) Default and Static Methods: Unlike traditional interfaces, functional interfaces can
include any number of default or static methods.
c) Compatibility with Lambda Expressions: Functional interfaces can be effortlessly
utilized with lambda expressions, method references, and constructor references.
d) Optional @FunctionalInterface Annotation: While the @FunctionalInterface
annotation is not mandatory, using it is beneficial. It acts as a tool for the compiler,
Object Oriented Programming With JAVA
ensuring that only one abstract method exists in the interface, thus enforcing the
functional interface contract.

Built-in Functional Interfaces

Java's powerful java.util.function package offers a variety of built-in functional


interfaces designed to make programming both flexible and efficient. Functional Interfaces
are the foundation of:
 Lambda Expressions
 Streams API
 Method References
 CompletableFuture API
 Event Handling
Interface Abstract Method Description
Evaluates a condition with the input, returning true or
Predicate<T> boolean test(T t)
false.
Consumer<T> void accept(T t) Processes input data without returning a result
Supplier<T> T get() Provides data output without taking any input.
Accepts one argument of type T and returns a result of
Function<T, R> R apply(T t)
type R.
BiFunction<T, U, Takes two arguments of potentially different types, T and
R apply(T t, U u)
R> U, and returns a result of type R.
A specialized Function where the type of input and output
UnaryOperator<T> T apply(T t)
is the same.
Similar to a BiFunction but both inputs and the result are
BinaryOperator<T> T apply(T t, T u)
of the same type T.
Example 1: Custom Functional Interface with Lambda
@FunctionalInterface
interface DisplayMsg {
void prints();
}
public class MyProg {
public static void main(String[] args) {
// Lambda expression for functional interface
DisplayMsg dm = () -> System.out.println("Hello, World!");
dm.prints();// Calling the method
}
}
Output:

Example 2: Using Built-in Predicate Functional Interface


import java.util.function.Predicate;
Object Oriented Programming With JAVA
public class MyProg {
public static void main(String[] args) {
Predicate<String> checkLength = str -> str.length() > 5;
System.out.println(checkLength.test("Programming")); // true
System.out.println(checkLength.test("Java")); // false
}
}
Output:

Example 3: Using Functional Interface and Method Reference


@FunctionalInterface
interface DisplayMsg {
void prints(String s);
}
public class MyProg {
public static void main(String[] args) {
// Using method reference instead of lambda
DisplayMsg dm = System.out::println;
dm.prints("Hello from main using Method Reference!");
}
}
Output:

Lambda Expression
A Lambda Expression in Java offers a streamlined way to define anonymous
functions. Introduced in Java 8, Lambda expressions simplify the coding process by removing
the necessity for anonymous classes. This advancement results in code that is not only
shorter but also more readable and efficient. Lambda expressions simplify the
implementation of functional interfaces, allowing you to write cleaner, more manageable
code. They enable you to treat functionality as an argument or pass code more dynamically.
Syntax:
(parameters) -> {body of the function}
Example:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.forEach(n -> System.out.println(n)); //In this example, n ->
System.out.println(n) is a lambda expression that iterates through the
collection, printing each number.
// Traditional method
public int add (int a, int b) {
return a + b;
}
Object Oriented Programming With JAVA
// Using Lambda Expression
(int a, int b) -> {return a + b;}
// Shorter version (no return & braces needed for single statements)
(a, b) -> a + b;
Example 1: Custom Functional Interface with Lambda
@FunctionalInterface
interface DisplayMsg {
void prints();
}
public class LambdaExample {
public static void main(String[] args) {
// Lambda expression for functional interface
DisplayMsg dm = () -> System.out.println("Hello, World!");
dm.prints();// Calling the method
}
}

Output:

Method Reference
In Java, method references offer a concise alternative to lambda expressions when
invoking existing methods. Rather than writing out a full lambda expression, you can simply
reference a method by name using the double colon (::) operator.it is introduced in Java 8
,comes embrace modern Java features like enhanced code readability and it is compatible
with functional Interfaces. Method References used because these reasons:
a) When a Lambda Expression calls a method without modifying its arguments
b) When using Streams, Collections API, and Functional Interfaces.
c) When you want cleaner and more readable code

Syntax:
ClassName::methodName
This is equivalent to
(param) -> object.method(param)

Types of Method References

1. Static Method Reference- Instead of using a lambda expression, you can directly
reference a static method from a class.
Example:
import java.util.function.Function;
public class MyProg {
public static void main(String[] args) {
//Function<Integer,Double>squareRoot=num ->Math.sqrt(num);//Lambda Expression
//or
Function<Integer, Double> squareRoot = Math::sqrt; // Method Reference
Object Oriented Programming With JAVA
System.out.println(squareRoot.apply(25)); // Output: 5.0
}
}
Output:

2. Instance Method Reference-We can refer to an instance method of an


object.
Example:
import java.util.function.Supplier;
public class MyProg {
public static void main(String[] args) {
String message = "Hello, World!";
Supplier<String> toUpper = () -> message.toUpperCase();// Lambda Expression
//or
Supplier<String> toUpper = message::toUpperCase;// Method Reference
System.out.println(toUpper.get()); // Output: HELLO, WORLD!
}
}
Output:

3. Instance Method Reference of an Arbitrary Object-This is used when


referring to a method of an arbitrary object of a specific type.
Example:
import java.util.Arrays;
import java.util.List;
public class MyProg {
public static void main(String[] args) {
List<String> names = Arrays.asList("Instance", "Method", "Reference");
//names.forEach(name -> System.out.println(name)); // Using lambda expression
//or
names.forEach(System.out::println); // Using method reference
}
}
Output:

4. Constructor Reference-We can refer to a constructor using ClassName::new,


which is useful in functional programming.
Object Oriented Programming With JAVA
Example:
import java.util.function.Supplier;
class Car {
Car() {
System.out.println("Inside Car class constructor");
}
}
public class MyProg {
public static void main(String[] args) {
// Supplier<Car> obj = () -> new Car(); // Lambda Expression
//or
Supplier<Car> obj = Car::new; // Constructor Reference
obj.get(); // Creates a Car object and prints “Inside Car class constructor”
}
}
Output:

You might also like