Java 8 Functional Programming - Part 2

2021/11/21

Introduction

In the previous post, I briefly summarized functional interfaces. In this one, I want to introduce the Java functional programming library — Vavr, which I’ve been kind of obsessed with lately. One thing to note: functional interfaces are the foundation of Vavr, so the minimum supported version is Java 8. Using Vavr can effectively reduce boilerplate and make your code much more elegant. On one hand, it fills in some of the gaps and rough edges in Java 8’s built-in functional APIs. On the other hand, it saves you from reinventing the wheel.

When I first heard the name Vavr, I thought it was weird. Why this name? Then I saw its official website, and I went silent. I seriously suspected the founding team had paid some clickbait naming experts for advice. Turns out, Vavr is just Java spelled backwards. That really does “overturn” Java…..

Vavr official website screenshot

Official website screenshot

image-20211121134906921

Official website screenshot after flipping it upside down

Next, I’ll go over some simple features of Vavr. To avoid turning this into a translation of the official docs, I’ll extract the key points and add some demos. I won’t go too deep into source code details — this is mainly about usage. If you’ve read this far and still don’t know what Vavr is useful for, here are the three important “disruptions” I think this library brings:

  1. Vavr provides enhanced function interfaces (more powerful and convenient than the ones built into the JDK).
  2. It provides many features (methods) built around functional interfaces.
  3. It provides a Scala-like collection library (immutable collections aligned with functional programming principles).

Also, all the code in this article has been uploaded to Github

Maven dependency

Vavr is still being updated, but 1.0 still hasn’t been released. The main branch is still on 0.10.x. As of the time of writing, the latest version is 0.10.4. If you want the newest version, you can check it here.

<dependency>
    <groupId>io.vavr</groupId>
    <artifactId>vavr</artifactId>
    <version>0.10.4</version>
</dependency>

Vavr doesn’t use any third-party dependencies — all the code is handwritten — which makes it really small, less than 1 MB.

image-20211121133544886

Downloaded from Maven Central

Enhancements to the Function interface

I introduced the JDK’s built-in functional interfaces in the previous post. Honestly, whether in terms of use cases or functionality, they’re a bit limited. Remember Function, right? Its abstract method is apply, and its job is to convert one type into another. But what if I want to take two different input types and convert them into a third type? If you’ve looked through the java.util.function package, you’d probably say there’s BiFunction. But what about three inputs? Four? At that point, do we just extend it ourselves?

Function(0….8) interfaces

Vavr gives us more extensible function types. For example, the Function family includes Function0 through Function8, meaning functions can accept up to 8 parameters. For example, here’s a simple concatenation:

  @Test
  public void multiFunctionTest() {
    Function4<String, String, Boolean, Integer, String> func =
        (country, name, isMan, score) -> String.format("%s-%s-%s-%d", country, name, isMan ? "男" : "女", score);
    System.out.println(func.apply("中国", "小明", true, 10));
  }
// 中国-小明-男-10

More functional features

Vavr also enhances functions beyond what the JDK provides, in addition to andThen() and compose(). Vavr’s interfaces include real functional programming closure features such as currying, lifting, memoization, and more. Let’s go through them one by one.

Composition

The JDK actually has this too. It’s basically the mathematical concept of function composition: the y of f(x) can become the x of g(x), i.e. g(f(x)).

There are two methods that can do this: andThen() and compose(). A quick demo makes it obvious.

@Test
public void andThenTest() {
  Function4<String, String, Boolean, Integer, String> func1 =
      (country, name, isMan, score) -> String.format("%s-%s-%s-%d", country, name, isMan ? "男" : "女", score);
  // andThen means taking func1's return value and then applying func2 to it
  Function4<String, String, Boolean, Integer, String> func2 = func1
      .andThen(str -> String.join(":", StrUtil.split(str, '-')));
  System.out.println(func2.apply("中国", "小明", true, 10));
}
// 中国:小明:男:10

There’s also compose, which is similar, but this method only exists on Function1. Essentially it just flips the execution order, but the idea is still function composition.

@Test
public void composeTest() {
  Function1<Long, String> func1 = num -> num + "%";
  // First execute the apply inside compose, then pass the result into func1.apply
  Function1<Double, String> func2 = func1.compose((Double num) -> Math.round(num));
  System.out.println(func2.apply(12.25));
}
// 12%

PartialApply

Partial application means that if a Function has 5 parameters and you pass only 2 into apply(), the compiler won’t complain — but apply also won’t execute the function directly. Instead, it generates another function. This new function only takes the remaining 3 parameters, with the first 2 fixed to the values you already provided. Show code:

@Test
public void partialApplyTest() {
  Function4<String, String, Boolean, Integer, String> func1 =
      (country, name, isMan, score) -> String.format("%s-%s-%s-%d", country, name, isMan ? "男" : "女", score);

  Function3<String, Boolean, Integer, String> func2 = func1.apply("中国");
  System.out.println(func2.apply("小明", true, 10));

  Function2<Boolean, Integer, String> func3 = func1.apply("中国", "小明");
  System.out.println(func3.apply(true, 10));

  Function1<Integer, String> func4 = func1.apply("中国", "小明", true);
  System.out.println(func4.apply(10));

  System.out.println(func1.apply("中国", "小明", true, 10));
}
// 中国-小明-男-10
// 中国-小明-男-10
// 中国-小明-男-10
// 中国-小明-男-10

Currying

Currying is the technique of transforming a function that takes multiple parameters into a function that takes a single parameter (the first parameter of the original function), and returns another function that accepts the remaining parameters and eventually returns the result. You only need to call curried() on the function. After that, each apply() can only take one value, and its return value is still another curried function. See the code below.

@Test
public void curriedTest() {
  Function4<String, String, Boolean, Integer, String> func1 =
      (country, name, isMan, score) -> String.format("%s-%s-%s-%d", country, name, isMan ? "男" : "女", score);

  Function1<String, Function1<Boolean, Function1<Integer, String>>> func2 = func1.curried().apply("中国");
  Function1<Boolean, Function1<Integer, String>> func3 = func2.apply("小明");
  Function1<Integer, String> func4 = func3.apply(true);
  String result = func4.apply(10);

  System.out.println(result);
}
// 中国-小明-男-10

This way, any function in the chain can be extended, greatly improving reusability and making invocation more convenient.

Memoization

The name says it all: cache the result of a function, and the next time it’s called, just return the result from the first computation. To use it, simply call the interface’s memoized() method.

Emmm… in practice, I don’t use this one that much. Even for a demo, I can only think of using a random number. It feels like there aren’t that many real project scenarios for it.

@Test
public void memorizeTest() {
  Function0<Double> hashCache = Function0.of(Math::random).memoized();

  double randomValue1 = hashCache.apply();
  System.out.println(randomValue1);
  double randomValue2 = hashCache.apply();
  System.out.println(randomValue2);

}
// 0.6590067689384973
// 0.6590067689384973

New features built on functional interfaces

Pattern matching

Good news, good news: Java 14 already supports pattern matching. What? Your company still hasn’t upgraded to 14? Oh, neither has mine…. But with Vavr, you can already get a Scala-like pattern matching experience. Java’s switch only works on constants and has a lot of restrictions. Although JDK 7 added support for String, it still compares using equals() under the hood, which means if you pass in null, you get an NPE directly instead of falling through to default. Pattern matching not only avoids these issues, but can also work on the return value of another function, which can save quite a bit of code.

  • Basic syntax demo

Put the variable you want to match inside Match(...), then after .of you start defining cases. Inside $() goes the expected match value, and after that comes the value to return if it matches. Note that pattern matching automatically breaks. If $() is empty, it works like the default case in switch.

@Test
public void showTest() {
  int input = 2;
  String result = Match(input).of(
      Case($(1), "one"),
      Case($(2), "two"),
      Case($(3), "three"),
      Case($(), "?"));
  System.out.println(result);
}
// two
  • Advanced syntax demo

$() actually has another overload that accepts a predicate function. Vavr has its own predicate functional interface with lots of methods. For example, isIn() in the code below is one of those predicate methods. Its return value is itself a predicate function, and it can match multiple values.

  • $(): A wildcard pattern similar to the default case in a switch statement. It handles the case where no match is found.
  • $(value): This is an equality pattern, where a value is simply compared against the input.
  • $(predicate): This is a conditional pattern, where the predicate function is applied to the input and the resulting boolean is used to decide the match.
@Test
public void isInTest() {
  int input = 1;
  String result = Match(input).of(
      Case($(isIn(0, 1)), "zero or one"),
      Case($(2), "two"),
      Case($(3), "three"),
      Case($(), "?"));
  System.out.println(result);
}
// zero or one
@Test
public void anyOfTest() {
  Integer year = 1990;
  String result = Match(year).of(
      Case($(anyOf(isIn(1990, 1991, 1992), is(1986))), "Age match"),
      Case($(), "No age match"));
  System.out.println(result);
}
// Age match
@Test
public void customTest() {
  int i = 5;
  List<Integer> container = Lists.newArrayList(1, 2, 3, 4);

  String result = Match(i).of(
    // This could be replaced with a method reference, but I used a lambda to make it easier to understand
      Case($(e -> container.contains(e)), "Even Single Digit"),
      Case($(), "Out of range"));
  System.out.println(result);
}
// Out of range
  • Side effect demo

Looking at the examples above, every case returns a value. But sometimes you match something and don’t need to return anything — you just want to do something through side effects. The code below looks a bit twisty, so let me explain briefly. At first, the second parameter of Case was a return value. But if you want side effects, you must pass a Supplier. Don’t ask me why, that’s just how it’s designed, so you have to use () ->. Then what do you return? Here we use the run() method. run() takes a Runnable as input and returns a Void, and that Void can be ignored. Note that this Void is provided by Vavr, not the JDK keyword void. You just need to put your side-effect code into a Runnable. And yes, Runnable is the standard one from java.lang, no need for me to explain that one.

@Test
public void sideEffectsTest() {
  int i = 4;
  Match(i).of(
      Case($(isIn(2, 4, 6, 8)), () -> run(() -> System.out.println("这是第一类"))),
      Case($(isIn(1, 3, 5, 7, 9)), () -> run(() -> System.out.println("这是第二类"))),
      Case($(), o -> run(() -> System.out.println("没有找到"))));
}

Try

Try is similar to the JDK’s try-catch. Code executed inside Try won’t throw exceptions outward. Both exceptions and normal return values are captured by Vavr and then returned through Try. The basic usage is Try.of(). Inside of, you pass a supplier — the input form is fixed as () ->, and the return value is whatever your function produces.

  • Basic demo
@Test
public void tryTest() {
  Try<Integer> result = Try.of(() -> 1 / 0);
  // Whether it failed
  System.out.println(result.isSuccess());
  // Get the exception cause; if there is no exception, calling this throws UOE
  System.out.println(result.getCause());
  // Get the return value; if there was an exception, returns null
  System.out.println(result.getOrNull());
  // Get the return value; if there was an exception, returns the default value
  System.out.println(result.getOrElse(0));
}
// false
// java.lang.ArithmeticException: / by zero
// null
// 0

It also comes with a lot of built-in methods. It’s a bit like the JDK’s Optional, kind of like a “container” too — except it contains behavior that may fail, allowing you to continue processing or provide fallback logic. For simple handling, I often use Try, because it’s really convenient.

For example, when calling JSON.parseObject(), I usually wrap it in try-catch to make things more robust — who knows what kind of garbage string upstream might send over. But try-catch looks pretty ugly. Wrapping it with Try feels much cleaner.

  @Test
  public void trySeniorTest() {
    List<Integer> list = Try.of(() -> JSON.parseArray("json", Integer.class))
        .getOrElse(Collections.emptyList());
    System.out.println(list);
  }
// []

Immutable collection classes

Tuple

As we all know, Java doesn’t have tuples. But sometimes tuples are just really useful. Vavr implements tuples through generics. You can create them using the static factory methods on Tuple, and with IDEA’s type inference or Java 10’s var, the efficiency boost is honestly amazing. The usage is also pretty similar to Scala.

A tuple is composed of different elements, and each element can store a different type of data. It’s kind of like a List with multiple generic types. For example, List<Integer> can only hold Integer, while Tuple<Integer, String> means it can hold both Integer and String. But usually the number of elements must be fixed, because each position has a specific type.

  • Basic usage

You can initialize one with Tuple.of. Just put the elements into of, and IDEA will automatically infer which TupleN it is. To access elements, you use _n, for example the first element is _1.

@Test
public void tupleTest() {
  Tuple2<Integer, String> t2 = Tuple.of(1, "1");
  System.out.println(t2._1);
  System.out.println(t2._2);
}
  • Other usage

Tuple is immutable. You can modify it or add to it, but every change operation returns a brand new tuple. Updating is simple: call updateX(). Appending is also simple: call append().

@Test
public void tupleSeniorTest() {
  Tuple2<Integer, String> t2 = Tuple.of(1, "1");
  System.out.println(t2);

  Tuple2<Integer, String> t2s = t2.update1(2);
  System.out.println(t2s);
  
  Tuple3<Integer, String, Double> t3 = t2.append(1.0);
  System.out.println(t3);
}

I really like tuples, because sometimes I’m lazy and don’t want to create a POJO for every little thing, and I definitely don’t want Maps flying around everywhere. Tuples are convenient and very clear — kind of a balance between the two. They’re especially elegant when used together with pattern matching. But!!! Please note: Vavr’s Tuple does not support Jackson or JSON serialization. I’ve already stepped on that landmine for you. Don’t use it for HTTP return values or RPC communication.

List/Set/Map

One very important feature of functional programming is immutability. The JDK’s Collections can make a collection immutable, but…. show code

@Test
public void collectionsTest() {
  List<Integer> list = Lists.newArrayList(1, 2, 3);
  System.out.println(list);
  List<Integer> unmodifiableList = Collections.unmodifiableList(list);
  System.out.println(unmodifiableList);

  list.add(1);
  System.out.println(list);
  System.out.println(unmodifiableList);

  unmodifiableList.add(1);
}
// [1, 2, 3]
// [1, 2, 3]
// [1, 2, 3, 1]
// [1, 2, 3, 1]
// 
// java.lang.UnsupportedOperationException

As you can see from the code above, the immutable list from Collections is just a shallow wrapper around the original list. If the original list changes, this so-called “immutable” list changes too.

  • Vavr’s list

Vavr’s list is created with List.of(). Once created, it’s immutable, but you can still add or remove elements. And as you’ve probably already guessed, every modification produces a brand new immutable list.

@Test
public void collectionsTest() {
  io.vavr.collection.List<Integer> list = io.vavr.collection.List.of(1, 2);
  // Add one element
  io.vavr.collection.List<Integer> appendList = list.append(3);
  // Drop one element
  io.vavr.collection.List<Integer> dropList = list.drop(1);
  
  // Convert to a mutable Java list
  List<Integer> javaList = list.asJava();
  
}

Also, Vavr’s list can use stream-like operators directly. You don’t need to call stream() first and then operate on a Stream. I can’t say it’s exactly the same as Scala, but honestly… it feels almost identical. It also provides many more functional APIs, such as:

  • take(Integer) take the first n values
  • tail() get everything except the head element
  • zipWithIndex() lets you access the index while iterating (no need for fori)
  • find(Predicate) query a value based on a condition; in the Java standard library you’d need filter + findFirst to do the same …..

Other functional programming features

Option

Alright, no more pretending — this Option is basically the same as the JDK’s Optional. The inspiration probably came from Guava’s Optional anyway. But Vavr’s Option is an interface with two implementations: Some and None. The former represents the state of having a value, and the latter represents the absence of a value. The way to use it is Option.of().

@Test
public void multiFunctionTest() {
  Integer num = null;
  Option<Integer> opt = Option.of(num);

  // Same as Optional
  Integer result = opt.getOrElse(0);
  System.out.println(result);

  // Returns true if it's None
  boolean isEmpty = opt.isEmpty();
  System.out.println(isEmpty);

  // Convert to Java Optional
  Optional<Integer> optional = opt.toJavaOptional();
}
// 0
// true

I didn’t include all the methods because there are too many. Most of them are the same as Optional, and some are common Vavr methods, not unique to Option.

Lazy

Lazy evaluation is also a feature of functional programming, especially heavily used in Scala. And after the first evaluation, the value gets cached. It can be very helpful for saving memory and improving performance.

In Scala this is done with a keyword, but how does Vavr do it in Java? Similar to Option, it wraps the value in a kind of “container” and loads it when accessed.

@Test
public void lazyTest() {
  // Put a random number into the Lazy container
  Lazy<Double> lazy = Lazy.of(Math::random);

  // Check whether it has already been evaluated
  System.out.println(lazy.isEvaluated());

  // Actually get the Lazy value
  System.out.println(lazy.get());

  // Check whether it has now been evaluated
  System.out.println(lazy.isEvaluated());

  // Get the Lazy value again
  System.out.println(lazy.get());
}
// false
// 0.896267693320266
// true
// 0.896267693320266

Closing thoughts

There are still some features I didn’t cover, such as Either, Future, Promise, Validation, and so on. On one hand, after reviewing this article, I realized it had already become way too long. On the other hand, the scenarios where I use those in actual projects are relatively rare. If people are interested, I could write an advanced Vavr article, because I honestly think each of those features deserves its own post. I started writing this in the afternoon, and by the time I got to the later sections it was already deep into the night. So for some of the later features, I definitely got lazy and shared a lot less than I originally planned 😂. I’ll leave that as a hole to fill next time.

Of course, if you’re genuinely interested, I highly recommend checking out resilience4j, a rate-limiting / circuit-breaking / fallback middleware written with Vavr to replace Hystrix. The code quality is seriously excellent. I think it’s one of the best materials available right now for learning functional programming. The only downside is that it’s pretty hard to chew through, because functional programming is one of those things that feels great to write but isn’t always very friendly to the reader.

References

  1. Vavr User Guide
  2. Vavr official blog
  3. Vavr official website

All articles in this blog, unless otherwise stated, are licensed under @Oreoft . Please indicate the source when reprinting!

Table of Contents