This article is an article that introduces an implementation example of a basic functional interface.
Normally, I would implement it in a lambda expression or use it in a Stream, but for the sake of simplicity, I dare to use a familiar method instead of using it.
I wish I could get the feeling that "methods go into variables". (Strictly speaking, it's a class)
There are 43 functional interfaces defined in the java.util.function package, but the first four are the basics to keep in mind. Other than these four, it is safe to think that they are extended types.
Supplier Someone who has something and gives it to me. The abstract method is get. No arguments, with return value.
import java.time.LocalDateTime;
import java.util.function.Supplier;
public class Main {
public static void main(String[] args) {
Supplier<LocalDateTime> s = LocalDateTime::now;
System.out.println(s.get()); // -> 2017-01-11T16:29:08.086
}
}
Consumer A person who processes what you receive. The abstract method is accept. With arguments, no return value.
import java.util.function.Consumer;
public class Main {
public static void main(String[] args) {
Consumer<String> c = System.out::println;
c.accept("test"); // -> test
}
}
Predicate A person who returns the truth of what he received. The abstract method is test. With arguments, with return value (Boolean only).
import java.util.function.Predicate;
public class Main {
public static void main(String[] args) {
Predicate<String> p = ""::equals;
System.out.println(p.test("foo")); // -> false
}
}
Function A so-called function that processes and returns what you receive. The abstract method is apply. There are arguments and there is a return value.
import java.util.function.Function;
public class Main {
public static void main(String[] args) {
Function<String, Integer> f = Integer::parseInt;
System.out.println(f.apply("55") + 45); // -> 100
}
}
Recommended Posts