Java 8 – Functional Programming

Functional programming contains the following key concepts:

  • Functions as first class objects
  • Pure functions
  • Higher order functions

Pure functional programming has a set of rules to follow too:

  • No state
  • No side effects
  • Immutable variables
  • Favour recursion over looping

All the rules may not be applied at all times but you can still benefit by functional programming

Higher Order Functions

A function is a higher order function if at least one of the following conditions are met:
1. The function takes one or more functions as parameters.
2. The function returns another function as result.

      
public class HigherOrderFunctionClass {

  public <T> TestFactory<T> createTestFactory
    (IProducer<T> prod, IConfigurator<T> config) {
      
      return () -> {
          T obj = prod.produce();
          config.configure(obj);
          return obj;
      }
    }
  }
      >
    

Functional Interfaces

A functional interface in Java is an interface that only has one abstract method. By an abstract method is meant only one method which is not implemented. An interface can have multiple methods, e.g. default methods and static methods, both with implementations, but as long as the interface only has one method that is not implemented, the interface is considered a functional interface.

Example of a functional interface:

      
public interface MyInterface {
    public void run();
}
      
      

Here is another example of a functional interface with a default method and a static method too:

      
public interface MyInterface2 {
    public void run();

    public default void doIt() {
        System.out.println("doing it");
    }

    public static void doItStatically() {
        System.out.println("doing it statically");
    }
}
        
      

Notice the two methods with implementations. This is still a functional interface, because only run() is not implemented (abstract). However, if there were more methods without implementation, the interface would no longer be a functional interface, and could thus not be implemented by a Java lambda expression.

Summary

In this article we learnt about the Java 8 Functional Programming, Higher Order functions, functional interfaces and its examples.
Hope you liked the article !