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:

Callable is a FunctionalInterface
package java.util.concurrent;

@FunctionalInterface    (1)
public interface Callable<V> {

    V call() throws Exception;
}
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.
Using lambda expression for SAM

If we want to create implementation for Callable interface, we can use lambda expression instead, as shown in following code:

Callable using lambda expression
Callable<String> aCallable = () -> "dummy";
Another example of SAM using lambda
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?

  1. Default methods in interface can have an implementation, so they are not counted as abstract.

  2. 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.

Comparator definition
@FunctionalInterface
public interface Comparator<T> {

    int compare(T o1, T o2);

    boolean equals(Object obj);
}

Using comparator using lambda expression is easy:

ComparatorExample.java
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:
  1. ION Trading Java Interview Questions
  2. Cracking core java interviews - question bank
  3. Sapient Global Market Java Interview Questions and Coding Exercise
  4. Java Concurrency Interview Questions
  5. Multi-threading Java Interview Questions for Investment Bank
  6. RBS Java Programming Interview Questions
  7. Goldman Sachs Java Interview Questions

Recommended books for interview preparation:

Find more on this topic: