Home > Software Development > Java 8 New Features: Method Reference

Java 8 New Features: Method Reference

March 31st, 2014 Leave a comment Go to comments

Coming with lambda feature in Java 8 is the method reference feature. It allows programmers to use methods as variables, and parameters to other methods. It works for class constructors too, where the method name is unanimously “new.’

There are four types of method references per Oracle documentation. Syntax wise, they all look similar with double colons as shown in the following sample code.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

As you’ll see, the sample code sort an array of Integer objects with two different ways. I picked Integer as the element for sorting simply because it’s part of standard library and everyone knows about it. More importantly, I don’t need to write another Java POJO class for the sample. :)

/* Copyright by Steve Jin. All Rights Reserved. */
package org.doublecloud.jave8demo.defaultmethod;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class MethodRef
   public static void main(String[] args)
    Integer[] a = new Integer[] { 100_000_000, -1, 1, 2, 3};
    Comparator<? super Integer> f = CompareUtil::compareByValue;
    Arrays.sort(a, f);
    for(Integer i : a)
    List<Integer> al = Arrays.asList(a);
    al.forEach(e -> System.out.println(e));
class CompareUtil
  public static int compareByValue(Integer a, Integer b)
    return a.compareTo(b);

As you can see, the compareByValue() method is assigned to a variable typed Comparator (this is really not needed but just to show it can be treated as a variable). The variable can then be used as parameter to the sort method.

In the second way of sorting, the array is converted as a List and the sort() method defined on the List then uses the method reference directly as CompareUtil::compareByValue.

Because of this feature and lambda, the Java 8 collector library has quite some changes, I think the biggest after the generics. Although it takes a bit time to get used to the new way, the benefit can be huge with cleaner code and lots of built-in functions to reference. If you are interested in finding out, you can take a look at the java.util.stream.Collectors which has many methods defined and meant for being referenced elsewhere.

In the next article, I will introduce the stream API for parallel processing large amount of data. Stay tuned.

  1. April 19th, 2014 at 08:33 | #1

    That is a great. I am converted to be a C# programmer for a few years.
    Java is improved a lot, but this method reference is in C# for a while.
    That is good to Java learn from C#, C# learn from Java.

  2. April 19th, 2014 at 11:25 | #2

    That is true. The companies behind also hire designers from each other. :)


  1. No trackbacks yet.