Top 5 Functional Interface Every Java Developer Should Learn

Hello guys, functional interface in Java are an important concept but not many developer pay enough attention to them. They learn lambda and method reference but the functional interface from java.util.function package. While its not really possible to learn all the functional interfaces on that package but you can learn a few more commonly used ones like Predicate, Supplier, Consumer etc and that's what you will learn in this article.  But, before we get to the top 5 functional interfaces that every Java developer should learn, let me tell you a bit about what Java really is. 

For those of you who don't know, Java is basically a general-purpose, class-based, object-oriented programming language that aims to have lesser implementation dependencies. You can also think of Java as a computing platform for application development. 

What sets Java apart is that it is fast, secure, and reliable. It can be used for developing Java applications with the help of laptops, data centers, game consoles, scientific supercomputers, and even cell phones.


5 Essential Functional Interfaces Every Java Developer Should Learn

A Java platform is basically a collection of programs that will help you develop and run Java programming applications. It is made up of an execution engine, a compiler, and a set of libraries. It is basically a set of computer software and specifications. 

Java was developed by James Gosling when he was working at Sun Microsystems. It was later acquired by the Oracle Corporation. 

Java can also be used for developing android applications, creating Enterprise Software, creating mobile java applications, creating scientific computing applications, Big Data analytics, programming hardware devices, and server-side technologies like Apache and GlassFish.

1. The Supplier Interface

The supplier interface has been around since Java 8 and is a part of the java.util.function package. It is used for implementing functional programming in Java. It has a function that does not take any argument but returns a result of the type T. 

Top 5 Functional Interface Every Java Developer Should Learn



You can use the get() method. Check out the following example. 

import java.util.function.Supplier;
  
public class Main {
    public static void main(String args[])
    {
  
        // This function returns a random value.
        Supplier<Double> randomValue = () -> Math.random();
  
        // Print the random value using get()
        System.out.println(randomValue.get());
    }
}

You will get an output like this:

0.5685808855697841


2. Consumer Interface

The Consumer Interface in Java represents a function that accepts one argument and produces a result. But most of the time, they do not return a value. The consumer interface is made up of two different functions: accept() and andThen()

The accept() method accepts one value and performs an operation:

// Java Program to demonstrate
// Consumer's accept() method

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;

public class Main {
	public static void main(String args[])
	{
		// Consumer to display a number
		Consumer<Integer> display = a -> System.out.println(a);

		// Implement display using accept()
		display.accept(10);

		// Consumer to multiply 2 to every integer of a list
		Consumer<List<Integer> > modify = list ->
		{
			for (int i = 0; i < list.size(); i++)
				list.set(i, 2 * list.get(i));
		};

		// Consumer to display a list of numbers
		Consumer<List<Integer> >
			dispList = list -> list.stream()
                      .forEach(a -> System.out.print(a + " "));

		List<Integer> list = new ArrayList<Integer>();
		list.add(2);
		list.add(1);
		list.add(3);

		// Implement modify using accept()
		modify.accept(list);

		// Implement dispList using accept()
		dispList.accept(list);
	}
}

3. Function

A functional interface in Java contains only one abstract method. It can exhibit only one functionality. You can use lambda expressions for representing the instance of a functional interface. It can have a number of default methods. 




Check out the following example to get a better understanding:

// Java program to demonstrate Implementation of
// functional interface using lambda expressions

class Test {
	public static void main(String args[])
	{

		// lambda expression to create the object
		new Thread(() -> {
			System.out.println("New thread created");
		}).start();
	}
}

You will get an output like this:

New thread created


4. Predicate

The predicate is a functional interface in Java that is defined in the java.util.function package. It can be used for improving the manageability of the code, unit-testing them separately. It also contains a lot of methods. 

For example, the isEqual(Object targetRef) method tests if two arguments are equal according to Objects.equals(Object, Object). See the following example to get a better understanding. 




static  Predicate isEqual(Object targetRef)
Returns a predicate that tests if two arguments are 
equal according to Objects.equals(Object, Object).
T : the type of arguments to the predicate
Parameters:
targetRef : the object reference with which to 
compare for equality, which may be null
Returns: a predicate that tests if two arguments 
are equal according to Objects.equals(Object, Object)

You can also use the and(Predicate Other) method:

default Predicate and(Predicate other)
Returns a composed predicate that represents a 
short-circuiting logical AND of this predicate and another.
Parameters:
other: a predicate that will be logically-ANDed with this predicate
Returns : a composed predicate that represents the short-circuiting 
logical AND of this predicate and the other predicate
Throws: NullPointerException - if other is null

For example, you can see my earlier article - Predicate Functional interface Example in Java


5. BiFunction

BiFunction is a functional interface in Java that was introduced in Java 8. It takes two arguments and returns an object. In the following example, it takes two Integers, and then returns an Integer, Double, or a List.


 


import java.util.Arrays;
import java.util.List;
import java.util.function.BiFunction;

public class Java8BiFunctionDemo {

    public static void main(String[] args) {

        // takes two Integers and return an Integer
        BiFunction<Integer, Integer, Integer> func = (x1, x2) -> x1 + x2;

        Integer result = func.apply(2, 3);

        System.out.println(result); // 5

        // take two Integers and return an Double
        BiFunction<Integer, Integer, Double> func2 = (x1, x2) -> Math.pow(x1, x2);

        Double result2 = func2.apply(2, 4);

        System.out.println(result2);    // 16.0

        // take two Integers and return a List<Integer>
        BiFunction<Integer, Integer, List<Integer>> func3 
                 = (x1, x2) -> Arrays.asList(x1 + x2);

        List<Integer> result3 = func3.apply(2, 3);

        System.out.println(result3);

    }

}

You will get an output like this:

5
16.0
[5]

Conclusion

If you liked this list of the 5 best functional interfaces that every Java developer should learn, feel free to share it with your friends and family. I have no doubt that the interfaces in this list will transform you from a complete beginner to a Java expert within a matter of weeks or months. 

There are a wide variety of examples in this list that will be beneficial to both absolute beginners as well as intermediate-level learners. 

You can also drop a comment if you have any doubts about Java Functional Interfaces, and we will get back to you as soon as possible. 

1 comment:

Feel free to comment, ask questions if you have any doubt.