Single Abstract Method (SAM) and Functional Interface in Java

Carvia Tech | December 16, 2019 | 2 min read | 76 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. Java Concurrency Interview Questions and Answers
  2. Top 50 Multi-threading Java Interview Questions for Investment Bank
  3. Goldman Sachs Java Interview Questions for Senior Developer
  4. RBS Java Programming Interview Questions
  5. Citibank Java developer interview questions
  6. ION Trading Java Interview Questions
  7. BlackRock Top Java Interview Questions: Investment Banking Domain


Find more on this topic:
Java Interviews image
Java Interviews

Interview - Product Companies, eCommerce Companies, Investment Banking, Healthcare Industry, Service Companies and Startups.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info