Java: function reference

Source: Internet
Author: User

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.





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.