Java: function reference
You can use Lambda expressions to create anonymous methods. However, this method may already exist, and you can use function reference. This makes the code structure clearer.
We know that a common step in greedy algorithms is sorting. Assume the following backpack class is available:
class Package{ private int weight; // ignore setter and getter}
We have a backpack array Package [] packages. If you want to sort them:
Arrays.sort(packages, new Comparator
(){ public int compare(Package a,Package b){ return Integer.valueOf(a.getWeight()).compareTo(Integer.valueOf(b.getWeight())); }});
A friend familiar with Lambda expressions can see at a glance that Comparator is a function interface. In this way, you can change:
Arrays.sort(packages, (Package a,Package b) ->{ return Integer.valueOf(a.getWeight()).compareTo(Integer.valueOf(b.getWeight());});
Now, we imagine that if the Package class has a static method like this:
public static int compageW(Package a,Package b){ return Integer.valueOf(a.weight).comPareTo(Integer.valueOf(b.weight));}
In this case, you can change the Body part of the Lambda expression:
Arrays.sort(packages, (a,b) -> Person.compareW(a,b));
Because lambda expressions reference existing functions, we can use function references.
Arrays.sort(packages,Person::caompareW);
The previous example is:Reference of static functions. Java 8 also supportsReferences to methods of a specific type of instance,Any type of object function reference,References to constructors.
It is also very easy to reference the method of a specific object instance. Assume that the compareW method is not static.
We can use,
Package p = new Package();Arrays.sort(packages, p::compareW);
Reference a method of a specific type of instance, for example,
String[] stringArray = { "Barbara", "James", "Mary", "John", "Patricia", "Robert", "Michael", "Linda" };Arrays.sort(stringArray, String::compareToIgnoreCase);
References to constructors,
In this example, the Oracle tutorial completes the replication between two sets.
public static
, DEST extends Collection
> DEST transferElements( SOURCE sourceCollection, Supplier
collectionFactory) { DEST result = collectionFactory.get(); for (T t : sourceCollection) { result.add(t); } return result;}
Supplier is a function interface, and only the get method is used to obtain objects.
Your call may be,
Set
rosterSetLambda = transferElements(roster, () -> { return new HashSet<>(); });
You can use function reference to simplify the process,
Set
rosterSet = transferElements(roster, HashSet
::new);
Finally, we will briefly describe the Supplier interface:
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.