[Java] The use of functional interfaces in Java

This article is for learning reference only!

Related tutorial address:

https://www.runoob.com/java/java8-functional-interfaces.html

https://www.cnblogs.com/dgwblog/p/11739500.html

https://www.developer.com/java/java-functional-interfaces/

insert image description here

An interface is a contract that defines a set of methods and their signatures. Any class can extend this interface and implement the methods of this interface. The Java programming language has provided support for interfaces since the earliest versions of the language.

Functional interfaces are a popular feature of Java, added to the Java language in version 8. They allow developers to create functions as first-class objects, which opens up new possibilities for creating reusable code and simplifying the development process.

This article will introduce functional interfaces, how they work, why they are useful, and some examples of how developers can use them in their projects.

What are functional interfaces in Java?

A functional interface in Java is an interface consisting of only one abstract method (that is, a method that is not implemented). Although this method must have a return type, it cannot accept parameters. The method must also be public and in an accessible class or interface.

In addition to an abstract method, you can create the following methods in Java's functional interface:

  • default method
  • static method
  • Methods inherited from Object class

Here is a simple code example of the Java functional interface:

@FunctionalInterface 
public interface MyFunctionalInterface 
{
    
     
  void doSomething(); 
} 

As you can see, the interface has only one abstract method.

How to write a comparator interface in Java

A common example of a functional interface is the Comparator interface, which is used to compare two objects. It has the following abstract methods:

int compare(T obj1, T obj2); 
Here's how the Comparer interface is defined in Java: 
@FunctionalInterface
public interface Comparator {
    
    
	int compare(T o1, T o2);
	boolean equals(Object obj);
	//其他方法...
}

The Comparator interface can be used to sort a list of objects** by their natural order or by a custom order you define. For example, a programmer can use the Comparator interface to sort a list of strings by their length:

List listStrings = Arrays.asList("ABC", "XYZ", "PQR"); 
listStrings.sort((s1, s2) -> s1.length() - s2.length());
System.out.println(listStrings);

You can also reverse the order of the list:

listStrings.sort((s1, s2) -> s2.length() - s1.length());
System.out.println(listStrings);

@FunctionalInterface annotation in Java

In Java 8, the annotation **@FunctionalInterface** marks an interface as a functional interface. If your interface contains more than one abstract method, you can use this annotation to mark the interface to generate a compiler error. Functional interfaces in Java are often used in lambda expressions, which can have multiple default methods.

It should be noted that the annotation **@FunctionalInterface is optional. If an interface contains an abstract method but is not annotated with @FunctionalInterface, it is still a functional interface and may be the target type of a lambda expression. This annotation prevents us from mistakenly modifying a functional interface to a non-functional interface, because the compiler will flag the error.

What are the benefits of functional interfaces in Java?

The most notable benefit of functional interfaces is that they create abstractions that multiple classes can use without copying and pasting code. This is especially useful when developers need to create complex abstractions with various methods and behaviors.

In Java, using functional interfaces, programmers can pass functions as parameters rather than reference objects, which reduces the amount of boilerplate code that must be written.

In functional programming , a piece of code can be thought of as data. This is where lambda expressions come into play. You can use lambda expressions to pass code to another function or object.

It should be noted that lambda expressions use functional interfaces as data types. Because there is only one abstract method in a functional interface, the implementation of that method becomes code that can be passed as an argument to another method.

Implement functional interfaces using anonymous inner classes

Before Java 8, programmers used anonymous inner classes or objects to implement such interfaces, as the following code sample shows:

class Test {
    
    
    public static void main(String args[])
    {
    
    
        new Thread(new Runnable() {
    
    
            @Override public void run()
            {
    
    
                System.out.println("Hello World!");
            }
        }).start();
    }
}

Built-in functional interfaces in Java

In addition to the Comparator and Runnable interfaces, there are many other built-in functional interfaces in Java 8, such as Callable , Predicate , Function , and Consumer . These interfaces can be found in the java.util.function package.

Here is a brief discussion of the most commonly used built-in interfaces in Java:

  • Comparator : Comparator is an interface that is used to compare two objects based on certain criteria. The java.util.Comparator class is used to implement this interface.
  • Runnable : It is an abstract class that implements the Runnable interface and provides an abstraction of running threads.
  • Callable : It represents a task that returns a single result value T , which can be accessed by calling its **call()** method.
  • Future : A Future represents an asynchronous operation whose result may not be available yet, but will eventually become available at some point in the future (when all pending activities have completed successfully or unsuccessfully).
  • Supplier : A supplier is simply a function that returns a value and takes no input parameters; these are also known as pure functions .
  • Predicate : The Predicate functional interface represents a predicate that returns true or false for some condition specified by a boolean parameter type T.
  • Consumer : The Consumer functional interface represents a function that accepts a parameter of type T and does not return a result.

How to Implement a Custom Functional Interface in Java

Functional interfaces can be created in two ways: By adding the **@FunctionalInterface annotation, an existing interface can be converted into a functional interface. Alternatively, a programmer can have an interface that contains only one abstract method. The following code sample is a complete example of how to define and use a functional interface in Java :**

@FunctionalInterface  
    interface Test{
    
      
        void display(String message);  
    }  
    public class TestImplementation implements Test{
    
      
        public void display(String message){
    
      
            System.out.println(message);  
        }  
        public static void main(String[] args) {
    
      
            TestImplementation obj = new TestImplementation();  
            obj.display("Hello World!");  
        }  
    }

END

The lambda expressions introduced in Java 8 provide new syntactic improvements over earlier versions and help eliminate boilerplate code in applications. Functional interfaces are first-class citizens of Java, and their implementations can be thought of as lambda expressions. Functional interfaces make it easier to write functional code by reducing the verbosity of anonymous inner classes.

Functional interfaces are a great way to add flexibility to your code. By using a functional interface, a coder can specify exactly what functionality you need from an object, and then have that object implemented by whatever class meets your requirements.

Guess you like

Origin blog.csdn.net/m0_47015897/article/details/131413303