Skip to main content

Functional Interface in Java

Functional Interface in Java

In this article, we are going to see what is a Functional Interface in Java, Also we are going to have a look on how we can create and use functional interface in java

Content of this article

What is Functional Interface in Java?

Functional Interface in Java is an interface which contains only one abstract method. Let see an example of Functional Interface in Java.
@FunctionalInterface
interface BookConstraint{
     boolean test(Book book);
}
Note : Functional interface in Java can be instantiate by lambda expressions, method references, or anonymous class. We will see later how we can instantiate the Functional Interface in java later in this post.

@FunctionalInterface Annotation

In the above example, the interface is marked with @FunctionalInterface annotation. The @FunctionalInterface annotation (Introduced in Java 8) can be used to optionally mark the Functional interface in Java and also generate compile time error if the conditions are not satisfying the requirements of the functional interface.
The conditions are :
  • The interface must be contains only one abstract method.
  • The abstract method should not be a default method in case of Java 8.

Java also provide some built in Functional Interface like :

  • Runnable interface of java.lang package with only run() abstract method
  • Comparator<T> interface of java.util package with only compare(T obj1 , T obj2) abstract method
  • ActionListener interface of java.awt.event package with only actionPerformed(ActionEvent e) abstract method

How to Instantiate Functional Interface in Java?

Using Anonymous Inner Class

Anonymous class is an inner class used to instantiate any Interface in Java, not just Functional Interfaces.

Example 1: Instantiate our BookConstraint Functional Interface using Anonymous Inner Class

BookConstraint javaBookConstraint = new BookConstraint() {
     @Override
     public boolean test(Book book) {
         return book.getTitle().contains("Java");
     }
};
Book book = new Book();
book.setTitle("Learn Java");
boolean isJavaBook = javaBookConstraint.test(book);
if (isJavaBook) {
     System.out.println("This a Java Book");
}

Example 2: Instantiate Runnable Functional Interface using Anonymous Inner Class

Runnable runnable = new Runnable() {
     @Override
     public void run() {
         System.out.println("Instantiate Runnable using Anonymous Inner Class");
     }
};
Thread thread = new Thread(runnable);
thread.start();

Example 3 : Instantiate Comparator Functional Interface using Anonymous Inner Class

Comparator<String> stringComparator = new Comparator<String>() {
     @Override
     public int compare(String str1, String str2) {
         return str1.compareTo(str2);
     }
};
List<String> list = Arrays.asList(
          "Runnable", "Comparator", "ActionListener", "BookConstraint");
Collections.sort(list, stringComparator);
// To Print the List in Sorted Order
list.forEach(System.out::println);

Using Lambda Expressions Java

Lambda Expressions are introduced in Java 8 to instantiate the Functional Interface. Read this article to know more about the: Lambda Expression in Java

Example 1: Instantiate our BookConstraint Functional Interface using Lambda Expressions Java

BookConstraint javaBookConstraint = book -> book.getTitle().contains("Java");
Book book = new Book();
book.setTitle("Learn Java");
boolean isJavaBook = javaBookConstraint.test(book);
if (isJavaBook) {
     System.out.println("This a Java Book");
}

Example 2: Instantiate Runnable Functional Interface using Lambda Expressions Java

Runnable runnable = () -> System.out.println("Instantiate Runnable using Anonymous Inner Class");
Thread thread = new Thread(runnable);
thread.start();

Example 3: Instantiate Comparator Functional Interface using Lambda Expressions Java

Comparator<String> stringComparator = (str1, str2) -> str1.compareTo(str2);
List<String> list = Arrays.asList(
          "Runnable", "Comparator", "ActionListener", "BookConstraint");
Collections.sort(list, stringComparator);
// To Print the List in Sorted Order
list.forEach(System.out::println);

New Functional Interface introduced in Java 8

Java 8 introduced various built-in Functional Interface, that can be used in common programming practices like to write method definition, conditional expressions etc. These all interfaces is the part of java.util.function package. Lets look few of them one-by-one.

Functions

The Function<T,R> is a Functional Interface in Java 8 is declared in java.util.function package, which is used to write method definition. The one and only abstract method declared in this interface is apply() method. This method takes an argument of T type and transform into the R type. Basically, this interface is treated as a function that takes an argument and convert it into the result.
@FunctionalInterface
public interface Function<T, R> {
     R apply(T t);
}
The Lambda expression attach with the Function will become the definition of the apply() method. For Examples :

Example 1: Function that takes a Book as argument and return its title

Function<Book, String> getBookTitle = book -> book.getTitle();
String title = getBookTitle.apply(book);

Example 2: Function that takes a String as argument and converts it into Uppercase

Function<String, String> toUpperCase = str -> str.toUpperCase();
String upperCaseTitle = toUpperCase.apply(title);
Note : We can also combine two or more Functions by using andThen() method and they will run into the sequence.

Example 3: Function that takes a Book as an argument then fetch its title and then convert it into Uppercase

Function<Book, String> getBookTitle = book -> book.getTitle();
Function<String, String> toUpperCase = str -> str.toUpperCase();
Function<Book, String> getBookTitleInUpperCase = getBookTitle.andThen(toUpperCase);
String upperCaseTitle = getBookTitleInUpperCase.apply(book);

Predicates

The Predicate<T> is a Functional Interface in Java 8 is declared in java.util.function package, which is used to write conditional expressions or boolean valued function.The only abstract method declared in this interface is test() method. This method takes an argument of T type and perform some test on the argument and return true of false.
@FunctionalInterface
public interface Predicate<T> {
     boolean test(T t);
}
The Lambda expression attach with the Predicate will become the definition of the test() method. For Examples :

Example 1: Predicate that takes a Book as an argument and checks whether it is a java book or not

Predicate<Book> isJavaBookPredicate = book -> book.getTitle().contains("Java");
boolean result = isJavaBookPredicate.test(book);

Example 2: Predicate that takes a Book as an argument and checks whether it's price under 500 or not

Predicate<Book> isUnder500Predicate = book -> book.getPrice() <= 500;
boolean result = isUnder500Predicate.test(book);
Note : We can also combine two or more Predicates by and/or methods
Predicate<Book> isJavaBookPredicate = book -> book.getTitle().contains("Java");
Predicate<Book> isUnder500Predicate = book -> book.getPrice() <= 500;
Predicate<Book> isJavaBookAndUnder500Predicate = isJavaBookPredicate.and(isUnder500Predicate);
Predicate<Book> eitherJavaBookOrUnder500Predicate = isJavaBookPredicate.or(isUnder500Predicate);

Suppliers

The Supplier<T> is a Functional Interface in Java 8 is declared in java.util.function package, is used to write suppliers which supply an output without any input value. The only abstract method declared in this interface is get() method. This method doesn't take any argument but returns an output of T type.
@FunctionalInterface
public interface Supplier<T> {
     T get();
}
The Lambda expression attach with the Supplier will become the definition of the get() method. For Examples :

Example 1: Supply a new book

Supplier<Book> bookSupplier = () -> new Book();
Book book = bookSupplier.get();
book.setTitle("Learn Java");
book.setPrice(450);

Example 2: Supply a new book with title and price

Supplier<Book> bookSupplier = () -> new Book("Learn Java", 450);
Book book = bookSupplier.get();

Example 3: Supply a new book with title and price using method

// Any Random method
Book createBook(String Title, int Price){
      return new Book(title, price);
}
--------------------------------------------------------------------------
Supplier<Book> bookSupplier = () -> createBook("Learn Java", 450);
Book book = bookSupplier.get();

Consumers

The Consumer<T> is a Functional Interface in Java 8 is declared in java.util.function package, is used to write a function which consumes something i.e., argument passed from outside. The only abstract method declared in this interface is accept() method. This method takes an argument of T type, consumes it but returns void output .
@FunctionalInterface
public interface Consumer<T> {
     void accept(T t);
}
The Lambda expression attach with the Consumer will become the definition of the accept() method. For Examples :

Example 1: Consumes a book

Consumer<Book> bookConsumer = book -> System.out.println(book.getTitle() + " : " + book.getPrice());

Example 2: Consumes a book using method

// Any Random method
void printBook(Book book)
      System.out.println(book.getTitle() + " : " + book.getPrice());
}
--------------------------------------------------------------------------
Consumer<Book> bookConsumer = book -> printBook(book);

Consumer used by forEach() of a list of book

// Any Random method
void printBook(Book book)
      System.out.println(book.getTitle() + " : " + book.getPrice());
}
--------------------------------------------------------------------------
List<Book> listOfBooks = new ArrayList<>();
listOfBooks.add("Learn Java" , 450);
listOfBooks.add("Learn C++" , 280);
listOfBooks.add("Learn Android" , 750);
Consumer<Book> bookConsumer = book -> printBook(book);
listOfBooks.forEach(bookConsumer);

Related Posts:


Conclusion

So, this is all about the Functional Interface in Java, we have seen what they are, how to create in using multiple ways and how to use them. Also, we have learned what are some pre-defined Functional Interface in Java that can be used in our day-to-day programming.

Comments

Popular posts from this blog

How HashMap works internally in java

How Hashmap works Internally in Java In this article, we are going to see how HashMap internally works in java. Also, we will have a look at what Java 8 made changes on the internal working of Hashmap to make it faster. What is Hashmap and Hashing in java? How Hashmap works Internally in Java is majorly dependent upon the Hashing Principle. So, Before going to learn how HashMap works internally in java, lets first understand what is HashMap and hashing. HashMap : A HashMap is a map used to store mappings of key-value pairs. Also, it works on the Principle of Hashing. To know more about the HashMap, visit this article: HashMap in Java Hashing Principle : Simply, Hashing is a method used to produce an integer value from an object and this integer value known as the hash value. In HashMap, the key object is used for Hashing.
Internal Struture of the HashMap in java For internal working of HashMap, HashMap maintains an array of bucket, each bucket is a linked-list and linked list is a li…

HashMap in Java

HashMap in Java In this article, we are going to learn about the most important class of Java known as HashMap. HashMap in java is the most used map interface and it is used in our regular or day-to-day programming practices.
What is HashMap in java? Lets first start with basic definition of HashMap,
HashMap is a map which store key-value pair, where each key is mapped with a value.
HashMap defined in java.util package and implements map interface which provides functionalities to perform basic operation like store, retrieve, size of the map etc. It is a part of Java Collection Framework. Time complexity of HashMap in Java? : Time complexity to store and retrieve data from the HashMap is O(1) in the Best Case. But it can be O(n) in the worst case and after the changes made in Java 8 the worst case time complexity can be O(log n) atmost. Internal working of HashMap in java HashMap maintains an array of the buckets, where each bucket is a linked-list and the linked list is a list of…

ArrayList in Java

ArrayList in Java In this article, we are going to discuss ArrayList in Java. ArrayList is a class from the Java Collection Framework and widely in our programs. We use ArrayList as a substitute for the array. So, it is important to know ArrayList in detail. We are going to see what is ArrayList in Java, how we can create the instance of ArrayList and the methods provided by the ArrayList in Java.

If you already familiar to ArrayList, you may learn common programs related to ArrayList.
Table of ContentsWhat is ArrayList in Java?Hierarchy of the ArrayList in java?How to create objects of ArrayList in Java?How to create an ArrayList of Custom Objects?How to iterate ArrayList in Java?How to get the elements by index from ArrayList in Java?How to check whether an elements is stored in the ArrayList in Java?How to remove elements from the ArrayList in Java?Few more methods of ArrayList in Java?
What is ArrayList in Java? ArrayList in Java is a List in which we can store and retrieve elemen…