Java8:lambda Simple Combat __java

Source: Internet
Author: User
Tags comparable static class

A lambda expression can be interpreted as an anonymous function: It does not have a name, but by the argument list , the function body , the return type , and of course there may be a list of exceptions that can be thrown .

The basic syntax for a lambda is

(parameters)-> expression

or (note the curly braces for the statement)

(parameters)-> {statements;}
Depending on the syntax rules above, which of the following is not a valid lambda expression.
(1) ()-> {}
(2) ()-> "Raoul" (
3) ()-> {return "Mario";}
(4) (Integer i)-> return "Alan" + i;
(5) (String s)-> {"Ironman";}

Answer: only 4 and 5 are invalid lambda.
(1) This lambda has no parameters and returns void. It is similar to a method in which the principal is empty: public void Run () {}.
(2) This lambda has no parameters and returns string as an expression.
(3) This lambda has no parameters and returns a string (using an explicit return statement).
(4) Return is a control flow statement. To make this lambda valid, you need to make curly braces as follows:
(Integer i)-> {return "Alan" + I;}.
(5) "Iron man" is an expression, not a statement. To make this lambda effective, you can remove curly braces
and semicolons as follows: (String s)-> "Iron man". Or if you like, you can use an explicit return
sentence as follows: (String s)->{return "Ironman";

Here we start with a sort problem--sort the apple list with a different sort strategy, and we're clear step-by-step from a primitive, rough solution.

A series of concepts are used here: behavioral parameterization, anonymous classes, lambda expressions, and method references .

The following is the definition of the Apple class:

    public static class Apple {
        private Integer weight = 0;
        Private String color = "";

        Public Apple (Integer weight, String color) {
            this.weight = weight;
            This.color = color;
        }

        Public Integer Getweight () {return
            weight;
        }

        public void Setweight (Integer weight) {
            this.weight = weight;
        }

        Public String GetColor () {return
            color;
        }

        public void SetColor (String color) {
            This.color = color;
        }

        Public String toString () {return
            ' apple{' + ' color= ' + color + ' \ ' + ', weight= ' + Weight + '} ';
        }
    
First step: Passing Code

The Java 8 API has provided us with a list of the sort methods available, and we don't have to implement it ourselves.

Then the hardest part has been taken care of. But how do you pass a sort policy to the sort method?
The signature of the sort method is this:

void sort (comparator<? Super E> C)

It requires a comparator object to compare two Apple. This is how policies are passed in Java: they must be wrapped in one object. We say that the behavior of sort is parameterized : The sort policy passed to it differs in its behavior .

List<apple> inventory = new Arraylist<> ();
public static class Applecomparator implements comparator<apple> {public
        int compare (Apple A1, Apple A2) {
            Return A1.getweight (). CompareTo (A2.getweight ());
        }
Inventory.sort (New Applecomparator ());
Step Two: Use Anonymous inner class

The first scenario can be optimized using an anonymous inner class, because a applecomparator comparer can be used once, and we don't need to create a separate class to implement it.

        Inventory.sort (New comparator<apple> () {public
            int compare (Apple A1, Apple A2) {return
                a1.getweight (). CompareTo (A2.getweight ());
            }
        );
Step Three: Use lambda expressions

Disadvantages of using anonymous inner classes:
1. It is often cumbersome and occupies a lot of code space, in other words, it is too verbose.
2. The logic is not very clear because it is confusing to use.
The lambda expression is introduced in Java 8, which provides a lightweight syntax for achieving the same goal: passing code . (On our issue is the delivery strategy, the List#sort () method implements different sorts according to different policies (code)).
In this example, the comparator represents the function descriptor (T, t)-> Int. Because we are comparing apples, it specifically represents the (Apple, Apple)-> Int.

Inventory.sort (Apple A1, Apple A2)-> a1.getweight (). CompareTo (A2.getweight ());

Because the Java compiler can infer the type of an LAMDBA expression parameter based on the context in which the lambda appears, our solution can be rewritten as:

Inventory.sort ((a1, A2)-> a1.getweight (). CompareTo (A2.getweight ()));

Here we are still not satisfied, comparator has a static helper method called comparing that can accept a function to extract the comparable key value and generate a comparator object.

    public static <t, U extends Comparable<? Super u>> comparator<t> comparing (
            function< Super T,? extends u> keyextractor)
    {
        Objects.requirenonnull (keyextractor);
        Return (comparator<t> & Serializable)
            (c1, C2)-> keyextractor.apply (C1). CompareTo ( Keyextractor.apply (C2));
    

It can be used like this (note that the lambda you pass now has only one parameter: The lambda describes how to extract the key values from the apple that need to be compared):

comparator<apple> C = comparator.comparing ((Apple a)-> a.getweight ());
Inventory.sort (c);

Here we can also change the code to a little more compact:

Static Guide Package
import static java.util.Comparator.comparing;
Inventory.sort (Comparing ((a)-> a.getweight ()));
Step Fourth: Use method references

A method reference is the syntactic sugar that replaces the lambda expression of those forwarding parameters. You can use method references to make your code more concise (assuming you statically import java.util.Comparator.comparing):

Inventory.sort (Comparing (apple::getweight));

method References let you reuse existing methods to implement and pass them directly.

Congratulations, this is your final solution. This is better than the code before Java 8.

It's shorter; it's very clear, and the code reads like the question: "Sort the inventory and compare the weight of the apple." ”

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.