JavaRush /Java Blog /Random EN /Coffee break #182. Functional Interfaces in Java

Coffee break #182. Functional Interfaces in Java

Published in the Random EN group
Source: DZone Here is an overview of functional interfaces in Java: purpose, examples, lambda expressions and a list of predefined interfaces. Coffee break #182.  Functional Interfaces in Java - 1As an object-oriented programming language, Java previously could not have independent functions because everything except some primitive data types and methods in the language revolves around classes and objects. However, Java 8 introduced a new concept called Functional Interface and also some other features like Lambda Expressions, Time API, Stream API and so on. What are these functional interfaces and how to define them? Let's find out!

What is an interface?

An interface is a set of rules that determine the interaction of system elements. It is also known as the outline of a class containing abstract methods and static constants. An interface may contain one or more abstract methods. Interfaces also allow you to set requirements for classes, that is, what methods are required from the class. Simply put, an interface is like a contract that must be adhered to by every implementing class. Here's an example:
Interface A1
{
void method1();
String method2(String X);
}

Class A1 implements A
{
@Override
public void method1(){}
@Override
public String method2(String X) { return x; }
}
If the class that implements the interface does not declare all of the interface's methods, the code will not run and will generate an error: “ error: A1 is not abstract and does not override an abstract method in A1. " (error: A1 is not abstract and does not override an abstract method in A1). Before JDK 8, interfaces could not define implementations, but now default implementations can be added for interface methods. We can also define static and default methods, which can call without an object in the interface Interfaces are mainly used to achieve multiple inheritance and loose coupling in code.Now that we have a clear understanding of interfaces, let's see what a functional interface is and how it works.

What is a functional interface?

The functional interface is also known as the Single Abstract Method (SAM) interface. As the name suggests, it can have at most one abstract method. A functional interface can have several static and default methods with an implementation, as well as an additional abstract method. To mark an interface as functional, the @FunctionalInterface annotation is used . It is needed to avoid erroneously declaring additional methods. What makes the functional interface so popular is the ability to use lambda expressions to create interfaces without using anonymous and cumbersome class implementations. The use of the abstract keyword in functional interfaces is optional because methods defined within an interface are abstract by default.

What are lambda expressions?

A lambda expression is an unnamed or anonymous method that does not execute on its own, but is used to implement certain methods of a functional interface. It is defined as follows:
(parameter list) -> lambda body
The arrow operator ( -> ) you see in code is known as the lambda operator. For example, if we have the following method:
double getGoldenRatioValue() {
return 1.61803;
}
Using a lambda expression, we can write it like this:
() -> 1.61803
As you can see, the method in the lambda function has no parameters, so the left side of the statement is empty. Since the right side determines the action, in this example it will return the value of the golden ratio: 1.61803. Before Java 8, implementing interfaces or creating inner class objects was crucial, but with Java 8, all we now need to do is assign lambda expressions to functional interfaces.

Examples of functional interfaces

To create functional interfaces, you can either use the @FunctionalInterface annotation or use Java's predefined functional interfaces.

Example 1

  • First, we'll tag @FunctionalInterface and create an interface called MyInterface that is called by the abstract getGoldenRationValue() method .
  • Then we will create a public class main to execute the method.
  • To use a lambda expression in a functional interface, we will declare a reference to MyInterfaceDemo and then assign the lambda expression to that reference.
  • Finally, we will print out the golden ratio value using the reference interface.
import java.lang.FunctionalInterface;

// Creation и маркировка функционального интерфейса
@FunctionalInterface

interface MyInterface {
// Это абстрактный метод
double getGoldenRatioValue();
}

public class Main {
public static void main( String[] args ) {

//декларируем ссылку на функциональный интерфейс
MyInterface ref;
//используем Lambda Expression
ref = () -> 1.61803;

System.out.println("Value of Golden Ratio = " + ref.getGoldenRatioValue());
}
}
Conclusion:
Value of Golden Ratio = 1.61803

Example 2

  • In this example, we are going to use the predefined function interface ToDoubleFunction , which takes a T argument and returns a double as output.
  • ToDoubleFuntion contains an abstract method called applyasDouble() .
  • Finally, we print the entire length of the message, including spaces.
import java.util.function.ToDoubleFunction;
public class MyInterface2 {

public static void main(String[] args) {

ToDoubleFunction<String> length = x -> x.length();

System.out.println(length.applyAsDouble("This is an example of predefined functional interface."));
}
}
Conclusion:
54.0

List of preinstalled functional interfaces

Now that we know how to define functional interfaces, let's see how many predefined (built-in) functional interfaces there are. There are 4 main types of functional interfaces that can be implemented in different situations: Consumer , Predicate , Function and Supplier . Among these four interfaces, Consumer , Function and Predicate have additional function interfaces. Here is a list of all the built-in or predefined interfaces in Java. Note. T, U and R mentioned in the table below represent the type of the first argument (T), second argument (U) and result (R) of the operation respectively.
Interface Type
Runnable
BiConsumer(T, U) T, U →
BiFunction(T, U, R) T, U → R
BinaryOperator T, T <→ R
BiPredicate<T, U> T, U → boolean
BooleanSupplier → boolean
Consumer T →
DoubleBinaryOperator double, double → double
DoubleConsumer double →
DoubleFunction double → R
DoublePredicate double → boolean
DoubleSupplier boolean →
DoubleToIntFunction double → int
DoubleToLongFunction double → long
DoubleUnaryOperator double → double
Function<T, R> T → R
IntBinaryOperator int → int
IntConsumer int →
IntFunction int → R
IntPredicate int → boolean
IntSupplier → int
IntToDoubleFunction int → double
IntToLongFunction int → long
IntUnaryOperator int → int
LongBinaryOperator long, long → long
LongConsumer long →
LongFunction long → R
LongPredicate long →
LongSupplier → long
LongToDoubleFunction long → double
LongToIntFunction long → int
LongUnaryOperator long → long
ObjDoubleConsumer T, double →
ObjIntConsumer T, int →
ObjLongConsumer T, long →
Predicate T → boolean
Supplier → T
ToDoubleBiFunction<T, U> T, U → double
ToDoubleFunction T → double
ToIntBiFunction<T, U> T, U → int
ToIntFunction T → int
ToLongBiFunction<T, U> T, U → long
ToLongFunction T → long
UnaryOperator T → T

Let's sum it up

Some key takeaways to remember from this post:
  • The interface works as an abstraction mechanism.
  • A functional interface can have several static and default methods with an implementation, as well as an additional abstract method.
  • Methods defined inside a functional interface are abstract by default, so using the abstract keyword is no longer necessary.
  • A lambda expression is an anonymous method that does not execute on its own, but is used to implement certain methods of a functional interface.
  • To create functional interfaces, you can either use the @FunctionalInterface annotation or use Java's predefined functional interfaces.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION