JavaRush /Java Blog /Random EN /Java functional interfaces
Алексей
Level 32

Java functional interfaces

Published in the Random EN group
A functional interface in Java is an interface that contains only 1 abstract method. The main purpose is to use it in lambda expressions and method references.
Java functional interfaces - 1
The presence of 1 abstract method is the only condition, so a functional interface can also contain defaultmethods static. You can add the @FunctionalInterface annotation to a functional interface. This is not required, but if this annotation is present, the code will not compile if there is more or less than 1 abstract method. It is recommended to add @FunctionalInterface. This will allow you to use the interface in lambda expressions without worrying that someone will add a new abstract method to the interface and it will cease to be functional. Java has built-in functional interfaces housed in the java.util.function. I will not dwell on them in detail. I note that the most frequently used are: Consumer<T> , Function<T,R> , Predicate<T> , Supplier<T> , UnaryOperator<T> and their Bi forms. More details can be found on the documentation page: Package java.util.function
import java.util.function.Predicate;

//Определяем свой функциональный интерфейс
@FunctionalInterface
interface MyPredicate {
    boolean test(Integer value);
}

public class Tester {
    public static void main(String[] args) throws Exception {
        MyPredicate myPredicate = x -> x > 0;
        System.out.println(myPredicate.test(10));   //true

        //Аналогично, но используется встроенный функциональный интерфейс java.util.function.Predicate
        Predicate<Integer> predicate = x -> x > 0;
        System.out.println(predicate.test(-10));    //false
    }
}
But it turns out there is one subtle point described in the Java Language Specification: “interfaces do not inherit from Object, but rather implicitly declare many of the same methods as Object.” This means that functional interfaces can additionally contain abstract methods defined in the class Object. The code below is valid, there will be no compilation or runtime errors:
@FunctionalInterface
public interface Comparator<T> {
   int compare(T o1, T o2);
   boolean equals(Object obj);
   // другие default or static методы
}
Be careful during the interview! Good luck!
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION