First class functions in Java 8

Raoul-Gabriel Urma

This is a guest post from Raoul-Gabriel Urma, a PhD candidate in Computer Science at the University of Cambridge. His research centers on programming languages and software engineering. Raoul has written over 10 peer-reviewed articles and given over 20 technical talks at international conferences. He has worked for large companies such as Google, eBay, Oracle, and Goldman Sachs, as well as for several startup projects – and has recently written a book on Java 8 in Action: Lambdas, Streams and functional-style programming by Manning.

Raoul also teaches a course on modern development with Java 8 at Skills Matter, alongside Jim Gough & Richard Warburton. At the end of this course, you will be ready to use Java 8 on your day job and be familiar with the cutting edge programming approaches which allow you to write more flexible and concise code. You can find out more information about the course here, or head to the Skills Matter page to book your place now!


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.

I hope this brief post has sparked some interest in Java 8! You can find a longer explanation in this 10min animated video we put together:

 


 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s