Java -- & gt; Lambda expressions, java -- lambda expressions

Source: Internet
Author: User
Tags stream api

Java --> Lambda expressions, java -- lambda expressions
I. functional interfaces

Function interfaces (functional interfaces are also called functional interfaces. They are actually the same thing ). To put it simply, a functional interface contains only one method. For example, Java. lang. Runnable and java. util. Comparator in the java standard library are typical functional interfaces.
Java 8 provides @ FunctionalInterface as annotation. This annotation is optional. As long as the interface complies with the functional interface standard (that is, the interface that contains only one method), the virtual opportunity is automatically judged, however, it is best to use the annotation @ FunctionalInterface to declare the interface, so as to avoid other team members mistakenly adding new methods to the interface.

Lambda in Java cannot appear independently. It requires a functional interface to store it. The method body of the lambda expression is actually the implementation of the function interface.

The following interface is a functional interface.

Package com. yztcedu. lambdademo_01; @ FunctionalInterface // after adding this annotation, the interface can only have one abstract method. Public interface A {void call ();}
Ii. lambda syntax

It consists of three parts:
1. A parameter separated by commas (,) is a method parameter in a function interface.
2. An arrow Symbol:->
3. The method body can be an expression and a code block.

(Parameters)-> expression or (parameters)-> {statements ;}

The following code shows that the code of lambda expression design is more concise and readable.

Package com. yztcedu. lambdademo_01; public class Demo1 {public static void main (String [] args) {runThreadByLambda (); runThreadByInnerClass ();} public static void runThreadByLambda () {/* Runnable is a functional interface with only one method run. 1. Because the run () method does not have any parameters, you do not need to declare the form parameter in the preceding (). 2. run returns the void, so no return is required. 3.-> the code written later is actually the code defined in the run method. Because there is only one line of code here, {} can also be omitted. If there are more than one row, it cannot be omitted. */Runnable runnable = ()-> System. out. println ("this is a Thread implemented by Lambda"); new Thread (runnable ). start ();} public static void runThreadByInnerClass () {Runnable runnable = new Runnable () {@ Overridepublic void run () {System. out. println ("this is a Thread implemented using an internal class") ;}}; new Thread (runnable ). start ();}}
Iii. Method reference

It is actually a simplified way of writing lambda expressions. The referenced method is actually the implementation of the lambda expression method body, and the syntax is very simple. The left side is the container (which can be the class name or Instance name), and the center is "::", the right side is the corresponding method name. As follows:

ObjectReference::methodName

Reference format of common methods:

  1. If it is a static method, it is ClassName: methodName. For example, Object: equals
  2. If it is an Instance method, it is Instance: methodName. For example, Object obj = new Object (); obj: equals;
  3. The constructor is ClassName: new.
Package com. yztcedu. lambdademo_01; public class Demo2 {public static void main (String [] args) {/** method reference */Runnable runnable = Demo2: run; new Thread (runnable ). start ();} public static void run () {System. out. println ("method reference code... ");}}

It can be seen that the doSomething method is the implementation of lambda expressions. The advantage is that if you think the lambda Method has a long experience and affects code readability, method reference is a solution.

Iv. default method-interface Improvement

Simply put, an interface can have an implementation method without the implementation class. You only need to add a default keyword before the method name.

Package com. yztcedu. lambdademo_01; @ FunctionalInterfacepublic interface A {void call (); default void fun () {System. out. println ("I am the code in interface default method 1");} default void fun2 () {System. out. println ("I am the code in method 2 of the interface by default ");}}

Why is this feature available? First, the previous interface is a double-edged sword. The advantage is that it is abstract-oriented rather than specific programming-oriented. The defect is that when you need to modify the interface, you need to modify all the classes that implement the interface, currently, the collection framework before java 8 does not have the foreach method. The common solution is to add new methods and implementations to the related interfaces in JDK. However, for a released version, you cannot add a new method to the interface without affecting the existing implementation. So the default method is introduced. They aim to make the interface not introduced incompatible with the existing implementation.

Differences between interfaces and abstract classes in Java 8

Similarities:
1. All are abstract types;
2. There can be implementation methods (previously the interface failed );
3. You do not need to implement classes or successors to implement all methods. (previously, no. The default methods in the interface do not need to be implemented by the implementer)
Differences
1. abstract classes cannot be inherited multiple times, and interfaces can be (whether multi-type inheritance or multi-behavior inheritance );
2. abstract classes and interfaces reflect different design concepts. In fact, the abstract class represents the "is-a" relation, and the interface represents the "like-a" relation;
3. the variables defined in the interface are of the public static final type by default and must be given the initial values. Therefore, the Implementation class cannot be redefined or changed. The variables in the abstract class are of the default type, the value can be redefined in the subclass or assigned again.

Summary: The default method facilitates the modification of interfaces without damaging the structure of the original implementation class. Currently, the java 8 Collection framework has greatly improved the default method, when we finally begin to use the lambdas expression of Java 8, it provides us with a smooth transitional experience. In the future, we may see more default method applications in API design.

5. Use the lambda improved collection framework for internal iteration in 5.1 sets
Package com. yztcedu. lambdademo_01; import java. util. arrayList; import java. util. list; public class Demo3 {public static void main (String [] args) {List <User> users = new ArrayList <User> (); users. add (new User (20, "James"); users. add (new User (22, ""); users. add (new User (10, "Wang Wu"); users. forEach (User user)-> System. out. println (user. getAge ()));}}
5.2 Stream API

Stream only represents the data Stream, and there is no data structure, so it can no longer be traversed after it is traversed once (this should be noted during programming, unlike Collection, number of times there is data in the traversal), its source can be Collection, array, io, and so on.

Stream provides a big data operation interface to make data operations easier and faster. It has filtering, ing, and reducing the number of traversal methods. These methods are divided into two types: the intermediate method and the terminal method. The "stream" abstraction should be inherently continuous, the intermediate method always returns Stream. Therefore, if we want to obtain the final result, we must use the endpoint operation to collect the final result of abortion. The difference between the two methods is to look at his return value. If it is Stream, it is an intermediate method; otherwise it is an endpoint method.

Filter

Filtering in data streams is the most natural operation we can think of first. The Stream interface exposes a filter method, which can accept the Predicate implementation that represents the operation to use a lambda expression that defines the filter condition.

Import java. util. stream. stream; public class StreamDemo {public static void main (String [] args) {List <User> users = new ArrayList <User> (); users. add (new User (20, "James"); users. add (new User (22, ""); users. add (new User (10, "Wang Wu"); Stream <User> stream = users. stream (); stream. filter (p-> p. getAge ()> 20); // filter those older than 20 }}
Map

If we filter some data, for example, when converting an object. The Map operation allows us to execute a Function implementation (Function <T, R> generic T, R represents the execution input and execution result respectively). It accepts input parameters and returns them.

Package com. yztcedu. lambdademo_01; import java. util. arrayList; import java. util. list; import java. util. stream. stream; public class StreamDemo {public static void main (String [] args) {List <User> users = new ArrayList <User> (); users. add (new User (20, "James"); users. add (new User (22, ""); users. add (new User (10, "Wang Wu"); Stream <User> stream = users. stream (); // all User objects older than 20 years old are converted to string 50 objects. Currently, the stream only contains string objects. Stream. filter (User user)-> user. getAge ()> 20). map (User user)-> {return "50 ";});}}
Count

The count method is the end method of a stream. It can make the final statistics of the stream results and return the long

Package com. yztcedu. lambdademo_01; import java. util. arrayList; import java. util. list; import java. util. stream. collector; import java. util. stream. stream; public class StreamDemo {public static void main (String [] args) {List <User> users = new ArrayList <User> (); users. add (new User (20, "James"); users. add (new User (22, ""); users. add (new User (10, "Wang Wu"); Stream <User> stream = users. stream (); long count = stream. Filter (User user)-> user. getAge ()> = 20 ). map (User user)-> {return "50 ";}). count (); // returns the number of elements in the stream. System. out. println (count );}}

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.