One minute to figure out the lambda in java8.

Source: Internet
Author: User

The project structure is like this

User is an ordinary Pojo class.

Usercompare is a class that implements the Comprator

Now we have a requirement: A list of user groups is sorted by user age. Implementation is not difficult, the code is as follows:

This method because the second parameter of the sort method is comparator so you write an implementation class (I am the Usercompare class here), and override the implementation of the interface.

JAVA8 provides lambda to simplify, with lambda programmers never work overtime!

Just now the comparator implementation class and some internal code are saved and replaced with lambda expressions.

In addition, IntelliJ will prompt you to change to a better wording.

How much code is in the implementation class, and how many lines of code you save.

Happy for a long while, in the end what is the principle? The JAVA8 is actually a new syntactic sugar.

We opened the definition of java1.8 comparator and found a class definition with one more @functionalinterface

Yes, more than 1.8 a concept is functionalinterface, this comparator is a functionalinterface

With this annotation, you can replace the lambda expression with the implementation class where you originally used it.

My level is limited, if you see this is not understood, can help to understand, figure 1 is the implementation of the class, figure 2 is the implementation of the class is not useless to erase the place.

By contrast, lambda expressions allow you to remove useless code! The least code, the same functionality!

One minute to figure out the lambda in java8.

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.