First Class Functions in Java 8

Written on June 12, 2016

Java 8 adds functions as a new form of value. What does this mean? Let’s look at a simple example.

Suppose you want to filter all the hidden files in a directory. You need to start writing a method that given a File will tell you whether it is hidden or not. Thankfully there’s such a method inside the File class called isHidden. It can be viewed as a function that takes a File and returns a boolean.

However, to use it you need to wrap it into a FileFilter object that you then pass to the File.listFiles method as follows:

File[] hiddenFiles = new File(".").listFiles(new FileFilter() {
  public boolean accept(File file) {
      return file.isHidden();
  }
});

Ouch, that’s pretty obscure! We already have a function isHidden that we could use, why do we have to wrap it up in a verbose FileFilter object?

In Java 8 you can rewrite that code as follows:

File[] hiddenFiles = new File(".").listFiles(File::isHidden);

Wow! Isn’t that cool? We already have the function isHidden available so we just “pass” it to the listFiles method. Our code now reads closer to the problem statement.

The use of File::isHidden is a rather special case of a new feature called method references in Java 8. Given that methods contain code (the executable body of a method), then using methods as values is like passing code around.

If you are interested in an intensive Java 8 training, check out our Modern Development with Java 8 training two-day course