package java.util.concurrent;
@FunctionalInterface (1)
public interface Callable<V> {
V call() throws Exception;
}
Single Abstract Method (SAM) and Functional Interface in Java
Upasana | December 16, 2019 | 2 min read | 387 views | Java 8
Interface that has single abstract method (SAM), is known as functional interface. We can supply a lambda expression whenever an object of an functional interface is expected.
Conceptually, a functional interface has exactly one abstract method. |
Example of functional interface:
1 | The compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration. |
If we want to create implementation for Callable interface, we can use lambda expression instead, as shown in following code:
Callable<String> aCallable = () -> "dummy";
class Worker {
ExecutorService executor = Executors.newSingleThreadExecutor();
public<T> Future<T> invoke(Callable<T> runnable) {
return executor.submit(runnable);
}
}
class Client {
public void execute() {
Worker worker = new Worker();
worker.invoke(() -> {
System.out.println("this is an lambda work");
return "result";
});
}
}
Aren’t all methods in Interface are abstract?
-
Default methods in interface can have an implementation, so they are not counted as abstract.
-
Interface can redeclare methods from the Object class, such as toString() and clone() method, these declarations do not make the abstract method since any implementation of the interface will have an implementation from java.lang.Object or elsewhere.
For example, java.util.Comparator
interface is a FunctionalInterface even though it overrides equals()
method from Object class.
@FunctionalInterface
public interface Comparator<T> {
int compare(T o1, T o2);
boolean equals(Object obj);
}
Using comparator using lambda expression is easy:
class ComparatorExample {
public void sortPeopleByNameAndAge() {
List<Person> people = Arrays.asList(
new Person(20, "Foo"),
new Person(19, "Jane"),
new Person(21, "Foo")
);
Collections.sort(people);
people.stream()
.sorted(Comparator
.comparing(Person::getName)
.thenComparing(Person::getAge)
).forEach(System.out::println);
}
}
That’s all.
Top articles in this category:
- ION Trading Java Interview Questions
- Cracking core java interviews - question bank
- Sapient Global Market Java Interview Questions and Coding Exercise
- Java Concurrency Interview Questions
- Multi-threading Java Interview Questions for Investment Bank
- RBS Java Programming Interview Questions
- Goldman Sachs Java Interview Questions