What's new in <java8 > About anonymous internal collections and lambda expressions

Source: Internet
Author: User

To be clear about lambda expressions in Java, you have to talk about anonymous inner classes to help understand the essence.

I. Anonymous INNER class

Anonymous inner classes are suitable for creating classes that only need to be used once, such as the command object that is required to describe the commands pattern, and the syntax of the anonymous inner class is a bit strange, when an anonymous inner class is created, an instance of the class is immediately created, and the definition of the class disappears immediately, and the anonymous inner class cannot be reused.

The syntax format is generally as follows:

New Implementation Interface () | Parent class Constructor (argument list) {

The class body part of an anonymous inner class

}

As can be seen from the above, anonymous inner classes must inherit a parent class, or implement an interface, but can inherit at most one parent class, or implement an interface.

There are two rules for anonymous inner classes:

1. An anonymous inner class cannot be an abstract class, because an anonymous inner class object is created immediately when the system creates an anonymized inner class, so the anonymous inner class is not allowed to be defined as an abstract class.

2. The anonymous inner class cannot define a constructor (Constructor), because the anonymous inner class does not have a class name, so the constructor cannot be defined, but the anonymous constructed class can define an initialization block that can be completed by the instance initialization block.

Example 1:

Interfacemyinter{ PublicString getName ();} Public classanonymoustest{ Public voidTest (Myinter i) {System.out.println ("The Content of this function is" +i.getname ()); }     Public Static voidMain (string[] args) {anonymoustest ta; Ta.test (NewMyinter () { PublicString GetName () {return"Anonymous Content"; }    });}

The code for implementing the class object that is equivalent to the above code is:

class Implements myinter{    public  String getName () {        return "Anonymous Class Content";    }}

Example 2:

Abstract classmyupperclass{PrivateString name;  Public AbstractString getName ();  PublicMyupperclass () {} PublicMyupperclass (String s) {name=s;}}////Abstract instead of Interface Public classanonymoustest{ Public voidTest (myupperclass m) {System.out.println ("The Content of this Method is" +m.getname ()); }    //////////////     Public Static voidMain (string[] args) {anonymoustest at; At.test (NewMyupperclass ("Abstract Class Derived Content"){             PublicString GetName () {return"Anonymousclass Derived Content";    }        }); }}

Two. Lambda expression

Lambda expressions are an important update for JAVA8 and a new feature that has long been awaited by developers. Lambda expressions support the use of blocks of code as parameters, and lambda expressions allow for more concise code to create an instance of an interface (which is called a functional interface) with only one abstract method.

Lambda expressions can be used to simplify the creation of anonymous inner class objects, so the code in example 1 above can be rewritten in the following form.

 public  class   anonymoustest{ public  void   Test (Myinter i) {System.out.println (" The Content of this Method i    S "+i.getname ());  ////////////////// public  Span style= "color: #0000ff;" >static  void   main (String []args) {anonym        Oustest at; At.test (() ->new  String ("Lambda Content"    

As you can see from the program above, the test method implemented by the lambda expression in this code is completely equivalent to the test method implemented by the anonymous inner class, but no longer requires a cumbersome code block to re-declare an anonymous class without needing to re-indicate the name of the overridden method. You do not need to give the return value type of the overridden method.
As can be seen from the above method, lambda expression instead of anonymous inner class, lambda code block will be implemented instead of implementing the method body of the abstract class, the syntax of the lambda expression is mainly composed of three parts:

(1) formal parameter list, if only one parameter can omit parentheses, when no parameter type can be used () or obj instead.

(2) arrow (-)

(3) The Code block section, if the code has only one row, you can omit the curly braces, otherwise use curly braces to mark the code portion of the lambda expression.

The type of the lambda expression, also known as the target type, is the target type of the lambda expression, which must be a function interface (functional interface). A functional interface represents an interface that contains only one abstract method. A functional interface can contain more than one default method, a class method, but only one abstract method. If you use an anonymous type inner class to create an instance of a functional interface, you only need to implement an abstract method, in which case a lambda expression can be used to create the object, and the object created by the expression is the function interface. (You can use @functionalinterface annotations to limit the function interface.)

# #表达式的目标类型必须是明确的函数式接口

# #lambda表达式只能为函数式接口创建对象, a lambda expression can only implement one method, so he can only create an object for an excuse (functional interface) with only one abstract method.

Another thing to note: object is not a functional interface

To ensure that the target type of a lambda expression is a clear functional interface, there are three common ways to do this:

# #将lambda表达式赋值给函数式接口类型的变量

# #将lambda表达式当作参数传递给需要函数式接口类型的参数的调用方法

# #使用函数式接口对lambda表达式进行强制的类型转换

Report:

A number of functional interfaces are scheduled under the Java.util.function package, typically containing the following 4 classes of interfaces.

Function: This type of interface usually contains an apply abstract method that handles the conversion of parameters and then returns a new value.

Consumer: This type of interface usually contains an accept abstract method, which is used to process parameters, but does not return a new value.

predicate: This type of interface usually contains a test abstract party method, which evaluates the processing of the parameters and returns a Boolean value

Supplier: This type of interface usually contains a getas*** abstract method, which has no parameters and returns a data value according to a logical operation.

What's new in <java8 > About anonymous internal collections and lambda expressions

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.