Functional Programming in Java

Stream and Optional classes - added to Java 8 - allow you to have some fun with functional programming. The problem is Java still misses quite a lot to be taken as a serious FP language. Lambda notation and two monads (Optional and Stream) are just the tip of the iceberg. This leads to arising of libraries like vavr or functionaljava - both deriving from purely functional language Haskell.

One of the first things you need to get rid of when trying to be more functional, is the attempt to unwrap the monad too early. It usually involves using methods like Optional.get() or Stream.collect() where there is yet no need. Sometimes though, Java doesn't help with that, so let me give you some custom code for the rescue. This article will bring you closer to the concept of method lifting. 

Calculations on Optionals

Suppose we have some nice API we would like to use to calculate numbers:

1
2
3
4
5
6
7
8
    public interface Math {

        int multiply(int a, int b);

        double divide(int a, int b);

        ..
    }

We would like to use it to do some calculations on numbers wrapped with Optional:


1
2
3
4
5
    public interface NumberProvider {

        Optional<Integer> getNumber();

    }

Let's say we want to write a method, which returns the result of the division of two numbers wrapped with Optional, or empty Optional if any one of them is empty (we skip the 0 divisor case here). It may look something like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public Optional<Double> divideFirstTwo(NumberProvider numberProvider, Math math) {
        Optional<Integer> first = numberProvider.getNumber();
        Optional<Integer> second = numberProvider.getNumber();
        if(first.isPresent() && second.isPresent()) {
            double result = math.divide(first.get(), second.get());
            return Optional.of(result);
        } else {
            return Optional.empty();
        }
    }

That's rather nasty. It involves a lot of code which the only purpose is to wrap and unwrap the Optional. Let's try to make it more functional:


1
2
3
4
5
  public Optional<Double> divideFirstTwo(NumberProvider numberProvider, Math math) {
        return numberProvider.getNumber()
                .flatMap(first -> numberProvider.getNumber()
                                         .map(second -> math.divide(first, second)));
    }

That's much better. It turns out that invoking flatMap on the first monad and map on the second one inside the lambda, can be extracted even further to the method called lift:


1
2
3
4
5
6
public interface Optionals {

    static <R, T, Z> BiFunction<Optional<T>, Optional<R>, Optional<Z>> lift(BiFunction<? super T, ? super R, ? extends Z> function) {
        return (left, right) -> left.flatMap(leftVal -> right.map(rightVal -> function.apply(leftVal, rightVal)));
    }
}

Lift is able to promote any function, which takes two arguments, to the function with the arguments and the result type wrapped with Optional. It actually adds Optional behavior to the function in such a way that if one of the arguments is empty, then the result will also be empty. If JDK extracted flatMap and map methods to some common interface, for example Monad, then we could write one lift function for every instance of Java monad (Stream, Optional, custom classes). Unfortunately, we need to do this copy pasting for every instance. The final code for divideFirstTwo becomes:


1
2
3
4
5
6
import static com.ps.functional.monad.optional.Optionals.lift;
...

    public Optional<Double> divideFirstTwo(NumberProvider numberProvider, Math math) {
        return lift(math::divide).apply(numberProvider.getNumber(), numberProvider.getNumber());
    }


Summary 

I hope this article encouraged you to play with functional style in Java. JDK needs to be greatly improved for the language to be called functional in the future. Unfortunately, Java 9 doesn't promise any major improvements besides just a few additional methods. Source code can be found here.
0

Add a comment

Paxos protocol simulation in Akka
Paxos protocol simulation in Akka
Don't sleep when you test!
Don't sleep when you test!
5 Less Known Cool Intellij Features
5 Less Known Cool Intellij Features
Simple Map Reduce concept implementation
Simple Map Reduce concept implementation
Kotlin null safety for Optional experienced
Kotlin null safety for Optional experienced
Understanding flatMap
Understanding flatMap
Verifying End-to-end Test Code Coverage using Jacoco Agent
Lifting functions to work with monads in Java
Lifting functions to work with monads in Java
Composing functions with java.util.function.Function.andThen() trick
Composing functions with java.util.function.Function.andThen() trick
1
Exception-free code using functional approach
Exception-free code using functional approach
1
Popular Posts
Popular Posts
About Me
About Me
Labels
Blog Archive
Loading
Dynamic Views theme. Powered by Blogger. Report Abuse.