This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The last Gwen Challenge in 2021

Please follow OpenCoder and make friends with me ~❤😘😁🐱🐉 😁

Lambda expressions

An overview of the

The official website describes lambda expressions

Liverpoolfc.tv: docs.oracle.com/javase/tuto…

​ One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear. In these cases, you’re usually trying to pass functionality as an argument to another method, such as what action should be taken when someone clicks a button. Lambda expressions enable you to do this, to treat functionality as method argument, or code as data.

One problem with anonymous classes is that if the implementation of anonymous classes is very simple, such as an interface that contains only one method, then the syntax of anonymous classes can be unwieldy and unclear. In these cases, you often try to pass functionality as a parameter to another method, such as what to do when someone clicks a button. Lambda expressions allow you to do just that, treating functionality as method parameters or code as data.

There are three meanings in the description

  • Lambda expressions are a simplification of anonymous classes
  • The premise for lambda
    • An interface
    • The interface contains a method
  • Understanding lambda expressions: Passing functions as arguments to another method

The sample code

  • Create and start a thread that implements Runnable as an anonymous inner class, overriding the run method

    public static void main(String[] args) {
        new Thread(new Runnable() { // Anonymous inner class
            @Override
            public void run(a) {
                System.out.println("I'm the code that the thread starts executing.");
            }
        }).start();
    }
    Copy the code
  • The Runnable interface has only one abstract method, run. Rewrite it with lambda expressions

    // @FunctionalInterface
    // public interface Runnable {
    // public abstract void run();
    // }
    public static void main(String[] args) {
        new Thread(() -> System.out.println("I'm the code that the thread starts executing.")).start();
    }
    Copy the code
  • instructions

grammar

The basic grammar

From the above example, using lambda expressions is a rewrite of the run method in the Runnable interface

Format :(abstract method argument list) -> {rewrite code}

The sample code

Removes elements greater than 3 from the collection

  • Anonymous inner class

    List<Integer> list = new ArrayList<>(Arrays.asList(1.2.3.4.5));
    list.removeIf(new Predicate<Integer>() {
        @Override
        public boolean test(Integer i) {
            return i > 3; }}); System.out.println(list);/ / [1, 2, 3]
    Copy the code
  • Lambda expressions

    List<Integer> list = new ArrayList<>(Arrays.asList(1.2.3.4.5));
    list.removeIf((Integer i) -> {return i > 3; }); System.out.println(list);/ / [1, 2, 3]
    Copy the code
  • instructions

Shorthand syntax

Shorthand for arguments

  • The number of abstract method parameters
    • Empty parameter: not omitted.
    • One argument: omitparenthesesTo omitThe parameter types.
      • Before omission :(Integer I) -> {}
      • I -> {}
    • Multiple parameters: omittedThe parameter types.
      • (String a, Integer b) -> {}
      • (a,b) -> {}

Short for method body

  • There is only one line of expression in the method body: ellipsisBraces, return, semicolon.
    • Before omission :(Integer I) -> {return I > 3; }
    • I -> I > 3

The sample code

  • Lambda expressions

    List<Integer> list = new ArrayList<>(Arrays.asList(1.2.3.4.5));
    list.removeIf((Integer i) -> {return i > 3; }); System.out.println(list);/ / [1, 2, 3]
    Copy the code
  • shorthand

    List<Integer> list = new ArrayList<>(Arrays.asList(1.2.3.4.5));
    list.removeIf(i -> i > 3);
    System.out.println(list); / / [1, 2, 3]
    Copy the code

Functional interface

An overview of the

Functional interface: An interface with an abstract method

The JDK provides an annotation for functional interfaces: @functionalInterface.

Annotations apply to an interface to verify that the interface is functional

The sample

  • The Inter interface contains two abstract methods

New functional interfaces in JDK 8

Add a new functional interface to the java.util.function package

Examples are Predicate, Supplier, Function, and Consumer

The principle of

The debug debugging

  • Demo.java

    public class Demo {
        public static void main(String[] args) {
            new Thread(() -> {
                System.out.println("I'm the code that executes after the thread starts."); }).start(); }}Copy the code
  • The debug operation

  • instructions

    • Run :748,Thread(java.lang) : Calls the run method in Thread
    • Run: 786-1115060 (org.example.Demo$$Lambda$1) : callDemo$$Lambda$1The run method in
    • lambda$main$0:10, Demo(org.example) : methodlambda$main$0The print statement was executed in
  • summary

    • The run method in the Demo$$Lambda$1 class calls the —–> Lambda$main$0 method ——-> code that executes a block of Lambda expression code (print statement)

Preserve the bytecode files generated by lambda statements

  • Java command + parameter. Generate a new class file on hard disk (Demo$$Lambda$1.class)

    java -Djdk.internal.lambda.dumpProxyClasses Demo.class
    Copy the code

  • Drag the file into the idea

    • Demo$$Lambda$1Is the implementation class of Runnable
    • Called in the run methodDemo.lambda$main$0()methods

The principle of understanding

Method References

An overview of the

The official website describes method references

Liverpoolfc.tv: docs.oracle.com/javase/tuto…

​ You use lambda expressions to create anonymous methods. Sometimes, however, a lambda expression does nothing but call an existing method. In those cases, it’s often clearer to refer to the existing method by name. Method references enable you to do this; they are compact, easy-to-read lambda expressions for methods that already have a name.

You can use lambda expressions to create anonymous methods. Sometimes, however, lambda expressions do nothing but call existing methods. In these cases, it is often clearer to refer to an existing method by name. Method references enable you to do this; They are compact, easy-to-read lambda expressions for methods that already have names.

There are two meanings in the description

  • Method reference, used in labMDA expressions
  • Premise: Lambda expressions do nothing but call existing methods. (Examples in the grammar section below)
    • Arguments in lambda expressions invoke methods
      • Example :(String s) -> s.tolowercase ()
    • Parameters in labMDA expressions are used as parameters for other methods
      • Example :(Ineger I) -> string.valueof (I)

grammar

Liverpoolfc.tv: docs.oracle.com/javase/tuto…

There are four kinds of method references:

Kind Syntax Examples
Reference to a static method ContainingClass::staticMethodName Person::compareByAge MethodReferencesExamples::appendStrings
Reference to an instance method of a particular object containingObject::instanceMethodName myComparisonProvider::compareByName myApp::appendStrings2
Reference to an instance method of an arbitrary object of a particular type ContainingType::methodName String::compareToIgnoreCase String::concat
Reference to a constructor ClassName::new HashSet::new

Four method references

species grammar The sample
Reference static methods Class name :: Static method name Person::compareByAge MethodReferencesExamples::appendStrings
A reference to an instance method of a particular object Object name :: Method name myComparisonProvider::compareByName myApp::appendStrings2
A reference to an instance method of an arbitrary object of a particular type Class name :: Method name String::compareToIgnoreCase String::concat
Reference constructor The name of the class: : new HashSet::new

The following example uses the Stream-related API, which we will discuss in detail in a future article.

  • Reference static methods

    // Convert the Integer in the collection to String and collect it in a new collection
    List<Integer> integerList = new ArrayList<>(Arrays.asList(1.2.3.4.5));
    List<String> stringList = integerList.stream()
        // The argument I takes to the String static method valueOf. And lambda expressions do nothing but call methods
        // .map(i -> String.valueOf(i))
        .map(String::valueOf) // reference the static method valueOf in the String class. Class name :: Static method name
        .collect(Collectors.toList());
    System.out.println(stringList);
    Copy the code
  • A reference to an instance method of a particular object

    public class Demo {
        public static void main(String[] args) {
            Test test = new Test();
            List<Integer> integerList = new ArrayList<>(Arrays.asList(1.2.3.4.5));
            integerList.stream()
                    /* 1. Unlike static methods, you need instance 2 of Test to use the show method. The argument I is taken as an argument to the test object show method 3. And the lambda expression does nothing but call the method */
                    // .forEach(i -> test.show(i));
                    .forEach(test::show); // reference the method show in the test object. Object name :: Method name}}class Test{
        public void show(Object o){ System.out.println(o); }}Copy the code
  • A reference to an instance method of an arbitrary object of a particular type

    // Uppercase the elements in the collection and collect them in the new collection
    List<String> list = new ArrayList<>(Arrays.asList("a"."b"."c"));
    List<String> list2 = list.stream()
        /* 1. The parameter s is the caller of the toUpperCase method 2. And lambda expressions do nothing but call methods 3. The referenced data type of parameter s is String */
        // .map(s -> s.toUpperCase())
        .map(String::toUpperCase) // Reference the toUpperCase method in the String class. Class name :: Method name
        .collect(Collectors.toList());
    Copy the code
  • Reference constructor

    // Turn the elements in the collection into Person objects and collect them in the new collection
    public class Demo {
        public static void main(String[] args) {
            List<String> stringList = new ArrayList<>(Arrays.asList("Zhang"."Bill"."Fifty"));
    
            List<Person> personList = stringList.stream()
                    /* 1. The argument s is taken as an argument to the Person class constructor. 2
                    // .map(s -> new Person(s))
                    .map(Person::new) // Reference the constructor in the Person class. The name of the class: : new.collect(Collectors.toList()); }}class Person{
        private String name;
    
        public Person(String name) {
            this.name = name; }}Copy the code

Next up

Stream apis and principles

Please follow OpenCoder and make friends with me ~❤😘😁🐱🐉 😁