0% found this document useful (0 votes)
515 views

Java 8 Notes

Lambda expressions are anonymous functions that can be used to implement functional interfaces. Lambda expressions are added in Java 8 and provide concise syntax for implementing interfaces with a single method. Lambda expressions can have zero, one, or multiple parameters and support various functionalities like treating code as data.

Uploaded by

Hitakshi Rupela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
515 views

Java 8 Notes

Lambda expressions are anonymous functions that can be used to implement functional interfaces. Lambda expressions are added in Java 8 and provide concise syntax for implementing interfaces with a single method. Lambda expressions can have zero, one, or multiple parameters and support various functionalities like treating code as data.

Uploaded by

Hitakshi Rupela
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

JAVA 8 Feature

Lambda Expressions
Lambda Expression basically expresses an instance of the functional
interface, in other words, you can say it provides a clear and concise way to
represent a method of the functional interface using an expression. Lambda
Expressions are added in Java 8.

In Java, Lambda expressions basically express instances of functional


interfaces (An interface with a single abstract method is called a functional
interface). Lambda Expressions in Java are the same as lambda functions
which are the short block of code that accepts input as parameters and
returns a resultant value. Lambda Expressions are recently included in Java
SE 8.
Functionalities of Lambda Expression in Java
Lambda Expressions implement the only abstract function and therefore
implement functional interfaces lambda expressions are added in Java 8 and
provide the below functionalities.
 Enable to treat functionality as a method argument, or code as data.
 A function that can be created without belonging to any class.
 A lambda expression can be passed around as if it was an object and
executed on demand.
Java Lambda Expression Example
 Java

// Java program to demonstrate lambda expressions

// to implement a user defined functional interface.

// A sample functional interface (An interface with

// single abstract method

interface FuncInterface
{

// An abstract function

void abstractFun(int x);

// A non-abstract (or default) function

default void normalFun()

System.out.println("Hello");

class Test

public static void main(String args[])

// lambda expression to implement above

// functional interface. This interface

// by default implements abstractFun()

FuncInterface fobj = (int x)->System.out.println(2*x);


// This calls above lambda expression and prints 10.

fobj.abstractFun(5);

Output
10

Lambda Expression Syntax


lambda operator -> body
Lambda Expression Parameters
There are three Lambda Expression Parameters are mentioned below:
1. Zero Parameter
2. Single Parameter
3. Multiple Parameters
1. Lambda Expression with Zero parameter
() -> System.out.println("Zero parameter lambda");

2. Lambda Expression with Single parameter


(p) -> System.out.println("One parameter: " + p);

It is not mandatory to use parentheses if the type of that variable can be


inferred from the context
0 seconds of 17 secondsVolume 0%

 Java
// A Java program to demonstrate simple lambda expressions

import java.util.ArrayList;

class Test {

public static void main(String args[])

// Creating an ArrayList with elements

// {1, 2, 3, 4}

ArrayList<Integer> arrL = new ArrayList<Integer>();

arrL.add(1);

arrL.add(2);

arrL.add(3);

arrL.add(4);

// Using lambda expression to print all elements

// of arrL

arrL.forEach(n -> System.out.println(n));

// Using lambda expression to print even elements

// of arrL

arrL.forEach(n -> {
if (n % 2 == 0)

System.out.println(n);

});

Output
1
2
3
4
2
4

Note: that lambda expressions can only be used to implement functional


interfaces. In the above example also, the lambda expression
implements Consumer Functional Interface.
3. Lambda Expression with Multiple parameters
(p1, p2) -> System.out.println("Multiple parameters: " + p1 + ", "
+ p2);

A Java program to demonstrate the working of a lambda expression with two


arguments.
 Java

// Java program to demonstrate working of lambda expressions

public class Test {

// operation is implemented using lambda expressions


interface FuncInter1 {

int operation(int a, int b);

// sayMessage() is implemented using lambda expressions

// above

interface FuncInter2 {

void sayMessage(String message);

// Performs FuncInter1's operation on 'a' and 'b'

private int operate(int a, int b, FuncInter1 fobj)

return fobj.operation(a, b);

public static void main(String args[])

// lambda expression for addition for two parameters

// data type for x and y is optional.


// This expression implements 'FuncInter1' interface

FuncInter1 add = (int x, int y) -> x + y;

// lambda expression multiplication for two

// parameters This expression also implements

// 'FuncInter1' interface

FuncInter1 multiply = (int x, int y) -> x * y;

// Creating an object of Test to call operate using

// different implementations using lambda

// Expressions

Test tobj = new Test();

// Add two numbers using lambda expression

System.out.println("Addition is "

+ tobj.operate(6, 3, add));

// Multiply two numbers using lambda expression

System.out.println("Multiplication is "

+ tobj.operate(6, 3, multiply));
// lambda expression for single parameter

// This expression implements 'FuncInter2' interface

FuncInter2 fobj = message

-> System.out.println("Hello " + message);

fobj.sayMessage("Geek");

Output
Addition is 9
Multiplication is 18
Hello Geek

Note: Lambda expressions are just like functions and they accept
parameters just like functions.
Conclusion
Some Important points intake from this article is mentioned below:
 The body of a lambda expression can contain zero, one, or more
statements.
 When there is a single statement curly brackets are not mandatory and
the return type of the anonymous function is the same as that of the body
expression.
 When there is more than one statement, then these must be enclosed in
curly brackets (a code block) and the return type of the anonymous
function is the same as the type of the value returned within the code
block, or void if nothing is returned.
FAQs in Lambda Expression
Q1. What type of lambda expression Java?
Answer:
Java Lambda Expressions are the short block of code that accepts input as
parameters and returns a resultant value.
Q2. Is it good to use lambda expressions in Java?
Answer:
Yes, using lambda expressions makes it easier to use and support other
APIs.
Q3. What are the drawbacks of Java lambda?
Answer:
Java lambda functions can be only used with functional interfaces.
Q4. Based on the syntax rules just shown, which of the following is/are
NOT valid lambda expressions?
1. () -> {}
2. () -> “geeksforgeeks”
3. () -> { return “geeksforgeeks”;)
4. (Integer i) -> return “geeksforgeeks” + i;
5. (String s) -> {“geeksforgeeks”;}
Answer:
4 and 5 are invalid lambdas, the rest are valid. Details:
1. This lambda has no parameters and returns void. It’s similar to a method
with an empty body: public void run() { }.
2. This lambda has no parameters and returns a String as an expression.
3. This lambda has no parameters and returns a String (using an explicit
return statement, within a block).
4. return is a control-flow statement. To make this lambda valid, curly braces
are required as follows: (Integer i) -> { return “geeksforgeeks” + i; }.
5. “geeks for geeks” is an expression, not a statement. To make this lambda
valid, you can remove the curly braces and semicolon as follows: (String
s) -> “geeks for geeks”. Or if you prefer, you can use an explicit return
statement as follows: (String s) -> { return “geeks for geeks”; }.

Java – Lambda Expressions Parameters


Lambda Expressions are anonymous functions. These functions do not need
a name or a class to be used. Lambda expressions are added in Java 8.
Lambda expressions basically express instances of functional interfaces An
interface with a single abstract method is called a functional interface. One
example is java.lang.Runnable.
Lambda expressions implement only one abstract function and therefore
implement functional interfaces. Predicate interface is an example of a
functional interface that has only one abstract method called test().
Illustration:
interface Predicate
{
......
abstract boolean test(T t)
}
The above is a functional interface that has one abstract method test
receiving only one parameter of type T and returns a boolean value. This
method is a generic method that takes a type parameter. This interface can
be implemented anywhere in a program using a lambda expression instead
of creating classes with multiple functions. For eg, to implement a runnable
interface used only for multithreading one needs to implement only a run()
method. Then there is the comparable interface which can be implemented
using compare() method.
Important points:

 The body of a lambda expression can contain zero, one, or more


statements.
 When there is a single statement curly brackets are not mandatory and
the return type of the anonymous function is the same as that of the body
expression.
 When there is more than one statement, then these must be enclosed in
curly brackets (a code block) and the return type of the anonymous
function is the same as the type of the value returned within the code
block, or void if nothing is returned.
These are for single–line lambda expressions having void return type.
Type 1: No Parameter.
Syntax:
() -> System.out.println("Hello");
It takes interface of the following form:
interface Test1
{
void print()
}
Type 2: Single Parameter.
Syntax:
(p) -> System.out.println(p);
It is not mandatory to use parentheses if the type of that variable can be
inferred from the context
It takes interface of the following form:
interface Test2
{
void print(Integer p)
}
The type and return type of the lambdas are automatically inferred.
Type 3: Multi parameters
(p1, p2) -> System.out.println(p1 + " " + p2);
It is not mandatory to use parentheses if the type of that variable can be
inferred from the context
It takes interface of the following form:
interface Test3
{
void print(Integer p1, Integer p2)
}
The type and return type of the lambdas are automatically inferred.
Now, we are done with discussing out the theoretical concept, now let us
come up with the implementation part. So here primarily we will be
discussing out the codes for the above three types as discussed above:
Note: forEach() method is of Iterable interface that is used to iterate through
a collection. Here it takes an argument of Consumer type interface. This is a
functional interface having only one abstract method called accept(). Since it
is a functional interface, a lambda expression can be passed.
Hence, if we do conclude out the above
Example 1: Lambda expression with no parameters
 Java

// Java code to illustrate lambda expression

// without parameters
// functional interface

// without parameters

interface Test1 {

void print();

class GfG {

// functional interface parameter is passed

static void fun(Test1 t) { t.print(); }

public static void main(String[] args)

// lambda expression is passed

// without parameter to functional interface t

fun(() -> System.out.println("Hello"));

Output
Hello
Example 2: Type 2 Lambda expression with a single parameter
 Java

// Java code to illustrate lambda expression


// with single parameter

// functional interface

// with one parameter of Integer type

interface Test2 {

// The void type and the Integer type

// is automatically inferred from here

// and assigned to the lambda expression

void print(Integer p);

class GfG {

// takes lambda expression and a variable of

// Integer type as arguments

static void fun(Test2 t, Integer p)

// calls the print function

t.print(p);

public static void main(String[] args)


{

// lambda expression is passed

// with a single parameter

// lambda expression is mapped to the

// single argument abstract function in the

// functional interface Test2

fun(p -> System.out.println(p), 10);

Output
10
Example 3: Type 3 Lambda expression with multi parameters
 Java

// Java code to illustrate lambda expression

// with multi parameters

// functional interface Test3

// with 2 parameter of Integer type

interface Test3 {

// The void type and the Integer type


// is automatically inferred from here

// and assigned to the lambda expression

void print(Integer p1, Integer p2);

class GfG {

// takes parameter of Test3 type followed

// by 2 integer parameters p1 and p2

static void fun(Test3 t, Integer p1, Integer p2)

// calls the print function

t.print(p1, p2);

public static void main(String[] args)

// lambda expression is passed

// with two parameters

// lambda expression is mapped to the

// double argument abstract function in the

// functional interface Test3

fun((p1, p2)
-> System.out.println(p1 + " " + p2),

10, 20);

Output
10 20
Example 4:Lambda expression with two parameters
 Java

// Demonstrate a lambda expression that takes two parameters

interface NumericTest2{

boolean test(int n, int d);

class GFG{

public static void main(String args[]){

// The lambda expression here determines if one number is the factor of another

NumericTest2 isFactor= (n,d) -> (n%d)==0;

if(isFactor.test(10,2))
System.out.println("2 is the factor of 10");

if(!isFactor.test(10,3))

System.out.println("3 is not a factor of 10");

Output
2 is the factor of 10
3 is not a factor of 10

Java Lambda Expression with Collections


In this article, Lambda Expression with Collections is discussed with
examples of sorting different collections like ArrayList, TreeSet, TreeMap,
etc. Sorting Collections with Comparator (or without Lambda): We can
use Comparator interface to sort, It only contains one abstract method: –
compare(). An interface that only contains only a single abstract method then
it is called a Functional Interface.
 Use of Comparator(I): –
 Prototype of compare() method: –
While defining our own sorting, JVM is always going to call Comparator to
compare() method.
 returns negative value(-1), if and only if obj1 has to come before obj2.
 returns positive value(+1), if and only if obj1 has to come after obj2.
 returns zero(0), if and only if obj1 and obj2 are equal.
In List, Set, Map, or anywhere else when we want to define our own sorting
method, JVM will always call compare() method internally. When there is
Functional Interface concept used, then we can use Lambda
Expression in its place. Sorting elements of List(I) with Lambda
Expression: – Using lambda expression in place of comparator object for
defining our own sorting in collections.
 Java
import java.util.*;

public class Demo {

public static void main(String[] args)

ArrayList<Integer> al = new ArrayList<Integer>();

al.add(205);

al.add(102);

al.add(98);

al.add(275);

al.add(203);

System.out.println("Elements of the ArrayList " +

"before sorting : " + al);

// using lambda expression in place of comparator object

Collections.sort(al, (o1, o2) -> (o1 > o2) ? -1 :

(o1 < o2) ? 1 : 0);

System.out.println("Elements of the ArrayList after" +

" sorting : " + al);

}
}

Sorting TreeSet using Lambda Expression:


 Java

import java.util.*;

public class Demo {

public static void main(String[] args)

TreeSet<Integer> h =

new TreeSet<Integer>((o1, o2) -> (o1 > o2) ?

-1 : (o1 < o2) ? 1 : 0);

h.add(850);

h.add(235);

h.add(1080);

h.add(15);

h.add(5);

System.out.println("Elements of the TreeSet after" +

" sorting are: " + h);

}
Sorting elements of TreeMap using Lambda Expression: Sorting will be
done on the basis of the keys and not its value.

 Java

import java.util.*;

public class Demo {

public static void main(String[] args)

TreeMap<Integer, String> m =

new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ?

-1 : (o1 < o2) ? 1 : 0);

m.put(1, "Apple");

m.put(4, "Mango");

m.put(5, "Orange");

m.put(2, "Banana");

m.put(3, "Grapes");

System.out.println("Elements of the TreeMap " +

"after sorting are : " + m);

It is also possible to specify a reverse comparator via a lambda


expression directly in the call to the TreeSet() constructor, as shown
here:
 Java

// Use a lambda expression to create a reverse comparator

import java.util.*;

class GFG{

public static void main(String args[]){

// Pass a reverse comparator to TreeSet() via a lambda expression

TreeSet<String> ts=new TreeSet<String>((aStr,bStr) -> bStr.compareTo(aStr));

// Add elements to the Treeset

ts.add("A");

ts.add("B");

ts.add("C");

ts.add("D");

ts.add("E");

ts.add("F");

ts.add("G");

//Display the elements .


for(String element : ts)

System.out.println(element + "");

System.out.println();

Output
G
F
E
D
C
B
A

Block Lambda Expressions in Java


Lambda expression is an unnamed method that is not executed on its own.
These expressions cause anonymous class. These lambda expressions are
called closures. Lambda’s body consists of a block of code. If it has only a
single expression they are called “Expression Bodies“. Lambdas which
contain expression bodies are known as “Expression Lambdas“. Below is an
example of Lambda expression in a single line.
Block Lambda contains many operations that work on lambda expressions
as it allows the lambda body to have many statements. This includes
variables, loops, conditional statements like if, else and switch statements,
nested blocks, etc. This is created by enclosing the block of statements in
lambda body within braces {}. This can even have a return statement i.e
return value.
Syntax: Lambda Expressions
(parameters) -> { lambda body }
Now first let us do understand the Lambda expression to get to know about
the block lambda expression.
Illustration:
In this case, lambda may need more than a single expression in its lambda
body. Java supports Expression Lambdas which contains blocks of code
with more than one statement. We call this type of Lambda Body a “Block
Body“. Lambdas that contain block bodies can be known as “Block
Lambdas“.
Example Representing the Lambda expression
 Java

// Java Program to illustrate Lambda expression

// Importing input output classes

import java.io.*;

// Interface

// If1 is name of this interface

interface If1 {

// Member function of this interface

// Abstract function

boolean fun(int n);

// Class

class GFG {
// Main driver method

public static void main(String[] args)

// Lambda expression body

If1 isEven = (n) -> (n % 2) == 0;

// Above is lambda expression which tests

// passed number is even or odd

// Condition check over some number N

// by calling the above function

// using isEven() over fun() defined above

// Input is passed as a parameter N

// Say custom input N = 21

if (isEven.fun(21))

// Display message to be printed

System.out.println("21 is even");

else
// Display message to be printed

System.out.println("21 is odd");

Output
21 is odd

Now switching over to the implementation of the block lambda expression


followed by two examples as shown below:

Implementation:

Example 1:

 Java

// Java Program to illustrate Block Lambda expression

// Importing all classes from


// java.util package

import java.io.*;

// Block lambda to find out factorial

// of a number

// Interface

interface Func {

// n is some natural number whose

// factorial is to be computed

int fact(int n);

// Class

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Block lambda expression

Func f = (n) ->


{

// Block body

// Initially initializing with 1

int res = 1;

// iterating from 1 to the current number

// to find factorial by multiplication

for (int i = 1; i <= n; i++)

res = i * res;

return res;

};

// Calling lambda function

// Print and display n the console

System.out.println("Factorial of 5 : " + f.fact(5));

Output
Factorial of 5: 120
Here in this block lambda declares a variable ‘res’, for loop and has return
statement which are legal in lambda body.

Example 2:

 Java

// Java Program to illustrate Block Lambda expression

// Importing all input output classes

import java.io.*;

// Interface

// Functional interface named 'New'

interface New {

// Boolean function to check over

// natural number depicting calendar year

// 'n' deepicting year is

// passed as an parameter
boolean test(int n);

// Class

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// block lambda

// This block lambda checks if the

// given year is leap year or not

New leapyr = (year) ->

// Condition check

// If year is divisible by 400 or the

// year is divisible by 4 and 100 both

if (((year % 400 == 0)

|| (year % 4 == 0) && (year % 100 != 0)))


// Returning true as year is leap year

return true;

else

// Returning false for non-leap years

return false;

};

// Calling lambda function over

// custom input year- 2020

// Condition check using the test()

// defined in the above interface

if (leapyr.test(2020))

// Display message on the console

System.out.println("leap year");

else

// Display message on the console

System.out.println("Non leap year");


}

Output
leap year

Functional Interfaces in Java


Java Functional Interfaces
A functional interface is an interface that contains only one abstract
method. They can have only one functionality to exhibit. From Java 8
onwards, lambda expressions can be used to represent the instance of a
functional interface. A functional interface can have any number of default
methods. Runnable, ActionListener, and Comparable are some of the
examples of functional interfaces.
Functional Interface is additionally recognized as Single Abstract Method
Interfaces. In short, they are also known as SAM interfaces. Functional
interfaces in Java are the new feature that provides users with the approach
of fundamental programming.
Functional interfaces are included in Java SE 8 with Lambda expressions
and Method references in order to make code more readable, clean, and
straightforward. Functional interfaces are interfaces that ensure that they
include precisely only one abstract method. Functional interfaces are used
and executed by representing the interface with an annotation
called @FunctionalInterface. As described earlier, functional interfaces can
contain only one abstract method. However, they can include any quantity of
default and static methods.

In Functional interfaces, there is no need to use the abstract keyword as it is


optional to use the abstract keyword because, by default, the method defined
inside the interface is abstract only. We can also call Lambda expressions as
the instance of functional interface.

Java Functional Interfaces Example

Example 1:
Before Java 8, we had to create anonymous inner class objects or implement
these interfaces.
 Java

// Java program to demonstrate functional interface

class Test {

public static void main(String args[])

// create anonymous inner class object

new Thread(new Runnable() {

@Override public void run()

System.out.println("New thread created");

}).start();

Output
New thread created
Example 2:
Java 8 onwards, we can assign lambda expression to its functional interface
object like this:
 Java
// Java program to demonstrate Implementation of

// functional interface using lambda expressions

class Test {

public static void main(String args[])

// lambda expression to create the object

new Thread(() -> {

System.out.println("New thread created");

}).start();

Output
New thread created

@FunctionalInterface Annotation

@FunctionalInterface annotation is used to ensure that the functional


interface can’t have more than one abstract method. In case more than one
abstract methods are present, the compiler flags an ‘Unexpected
@FunctionalInterface annotation’ message. However, it is not mandatory to
use this annotation.
Below is the implementation of the above topic:
 Java
// Java program to demonstrate lambda expressions to

// implement a user defined functional interface.

@FunctionalInterface

interface Square {

int calculate(int x);

class Test {

public static void main(String args[])

int a = 5;

// lambda expression to define the calculate method

Square s = (int x) -> x * x;

// parameter passed and return type must be

// same as defined in the prototype

int ans = s.calculate(a);


System.out.println(ans);

Output
25

Some Built-in Java Functional Interfaces


Since Java SE 1.8 onwards, there are many interfaces that are converted
into functional interfaces. All these interfaces are annotated with
@FunctionalInterface. These interfaces are as follows –
 Runnable –> This interface only contains the run() method.
 Comparable –> This interface only contains the compareTo() method.
 ActionListener –> This interface only contains the actionPerformed()
method.
 Callable –> This interface only contains the call() method.
Java SE 8 included four main kinds of functional interfaces which can
be applied in multiple situations as mentioned below:
1. Consumer
2. Predicate
3. Function
4. Supplier
Amidst the previous four interfaces, the first three interfaces,i.e., Consumer,
Predicate, and Function, likewise have additions that are provided beneath

1. Consumer -> Bi-Consumer
2. Predicate -> Bi-Predicate
3. Function -> Bi-Function, Unary Operator, Binary Operator
1. Consumer
The consumer interface of the functional interface is the one that accepts
only one argument or a gentrified argument. The consumer interface has no
return value. It returns nothing. There are also functional variants of the
Consumer — DoubleConsumer, IntConsumer, and LongConsumer. These
variants accept primitive values as arguments.
Other than these variants, there is also one more variant of the Consumer
interface known as Bi-Consumer.
Bi-Consumer – Bi-Consumer is the most exciting variant of the Consumer
interface. The consumer interface takes only one argument, but on the other
side, the Bi-Consumer interface takes two arguments. Both, Consumer and
Bi-Consumer have no return value. It also returns nothing just like the
Consumer interface. It is used in iterating through the entries of the map.

Syntax / Prototype of Consumer Functional Interface –


Consumer<Integer> consumer = (value) -> System.out.println(value);
This implementation of the Java Consumer functional interface prints the
value passed as a parameter to the print statement. This implementation
uses the Lambda function of Java.

2. Predicate
In scientific logic, a function that accepts an argument and, in return,
generates a boolean value as an answer is known as a predicate. Similarly,
in the Java programming language, a predicate functional interface of Java is
a type of function that accepts a single value or argument and does some
sort of processing on it, and returns a boolean (True/ False) answer. The
implementation of the Predicate functional interface also encapsulates the
logic of filtering (a process that is used to filter stream components on the
base of a provided predicate) in Java.
Just like the Consumer functional interface, Predicate functional interface
also has some extensions. These are IntPredicate, DoublePredicate, and
LongPredicate. These types of predicate functional interfaces accept only
primitive data types or values as arguments.
Bi-Predicate – Bi-Predicate is also an extension of the Predicate functional
interface, which, instead of one, takes two arguments, does some
processing, and returns the boolean value.
Syntax of Predicate Functional Interface –
public interface Predicate<T> {

boolean test(T t);

}
The predicate functional interface can also be implemented using a class.
The syntax for the implementation of predicate functional interface using a
class is given below –
public class CheckForNull implements Predicate {

@Override
public boolean test(Object o) {
return o != null;

}
}
The Java predicate functional interface can also be implemented using
Lambda expressions. An example of the implementation of the Predicate
functional interface is given below –
Predicate predicate = (value) -> value != null;
This implementation of functional interfaces in Java using Java Lambda
expressions is more manageable and effective than the one implemented
using a class as both the implementations are doing the same work, i.e.,
returning the same output.

3. Function
A function is a type of functional interface in Java that receives only a single
argument and returns a value after the required processing. There are many
versions of Function interfaces because a primitive type can’t imply a general
type argument, so we need these versions of function interfaces. Many
different versions of the function interfaces are instrumental and are
commonly used in primitive types like double, int, long. The different
sequences of these primitive types are also used in the argument.
These versions are:
Bi-Function
The Bi-Function is substantially related to a Function. Besides, it takes two
arguments, whereas Function accepts one argument.
The prototype and syntax of Bi-Function is given below –
@FunctionalInterface
public interface BiFunction<T, U, R>
{

R apply(T t, U u);
.......

}
In the above code of interface, T and U are the inputs, and there is only one
output which is R.
Unary Operator and Binary Operator
There are also two other functional interfaces which are named Unary
Operator and Binary Operator. They both extend the Function and Bi-
Function, respectively. In simple words, Unary Operator extends Function,
and Binary Operator extends Bi-Function.

The prototype of the Unary Operator and Binary Operator is mentioned


below :
i. Unary Operator
@FunctionalInterface
public interface UnaryOperator<T> extends Function<T, U>
{
……...
}
ii. Binary Operator
@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T, U, R>
{
……...
}
We can understand front the above example that the Unary Operator
accepts only one argument and returns a single argument only. Still, in
Unary Operator both the input and output values must be identical and of the
same type.
On the other way, Binary Operator takes two values and returns one value
comparable to Bi- Function but similar to a Unary Operator, the input and
output value types must be identical and of the same type.

4. Supplier
The Supplier functional interface is also a type of functional interface that
does not take any input or argument and yet returns a single output. This
type of functional interface is generally used in the lazy generation of values.
Supplier functional interfaces are also used for defining the logic for the
generation of any sequence. For example – The logic behind the Fibonacci
Series can be generated with the help of the Stream. generate method,
which is implemented by the Supplier functional Interface.
The different extensions of the Supplier functional interface hold many other
suppliers functions like BooleanSupplier, DoubleSupplier, LongSupplier, and
IntSupplier. The return type of all these further specializations is their
corresponding primitives only.
Syntax / Prototype of Supplier Functional Interface is –
@FunctionalInterface
public interface Supplier<T>{

// gets a result
………….

// returns the specific result


…………

T.get();

}
Below is the implementation of the above topic:
 Java

// A simple program to demonstrate the use

// of predicate interface

import java.util.*;

import java.util.function.Predicate;

class Test {

public static void main(String args[])

// create a list of strings

List<String> names = Arrays.asList(


"Geek", "GeeksQuiz", "g1", "QA", "Geek2");

// declare the predicate type as string and use

// lambda expression to create object

Predicate<String> p = (s) -> s.startsWith("G");

// Iterate through the list

for (String st : names) {

// call the test method

if (p.test(st))

System.out.println(st);

Output
Geek
GeeksQuiz
Geek2
Important Points/Observations:
Here are some significant points regarding Functional interfaces in Java:
1. In functional interfaces, there is only one abstract method supported. If
the annotation of a functional interface, i.e., @FunctionalInterface is not
implemented or written with a function interface, more than one abstract
method can be declared inside it. However, in this situation with more
than one functions, that interface will not be called a functional interface.
It is called a non-functional interface.
2. There is no such need for the @FunctionalInterface annotation as it is
voluntary only. This is written because it helps in checking the compiler
level. Besides this, it is optional.
3. An infinite number of methods (whether static or default) can be added to
the functional interface. In simple words, there is no limit to a functional
interface containing static and default methods.
4. Overriding methods from the parent class do not violate the rules of a
functional interface in Java.
5. The java.util.function package contains many built-in functional
interfaces in Java 8.

You might also like