JAVA-->LAMBDA-expression

Source: Internet
Author: User
Tags instance method stream api

First, the function type interface

The function interface (functional interface is also called the functional interface, is actually the same thing). In simple terms, a functional interface is an interface that 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 annotations, this annotation is not necessary, as long as the interface conforms to the standard of the functional interface (that is, an interface that contains only one method), the virtual opportunity is automatically judged, but It is best to use annotation @functionalinterface on the interface to make the declaration so that other people in the team mistakenly add new methods to the interface.

Lambda in Java cannot appear alone, it requires a functional interface to be put in, the lambda expression method body is actually the implementation of the function interface.

The following interface is a function-type interface

package com.yztcedu.lambdademo_01;@FunctionalInterface //添加此注解后,接口中只能有一个抽象方法。public interface A {void call();}
Second, lambda syntax

Contains three parts:
1, a comma-delimited form parameter in parentheses, parameter is the parameter of the method inside the function interface
2, an arrow symbol:->
3, method body, can be an expression and code block.

(parameters) -> expression 或者 (parameters) -> { statements; }

You can see that the code for lambda expression Design is more concise and more readable with the following code.

Package com.yztcedu.lambdademo_01;PublicClassDemo1 {PublicStaticvoidMain(string[] args) {Runthreadbylambda (); Runthreadbyinnerclass ();}PublicStaticvoidRunthreadbylambda() {/* runnable is a functional interface: He has only one method of the run () method. 1. Because the run () method has no parameters, it is not necessary to declare parameter 2 in the front (), and run returns void, so no return is required. 3, the code behind the write is actually defined in the Run method within the code. Because there is only one line of code here, {} can also be omitted. If there is more than one row here, you cannot omit it. */runnable Runnable = (), System.out.println ("This is a thread implemented with lambda"); new Thread (runnable). Start ();} public static void Runthreadbyinnerclass() {Runnable Runnable = new Runnable () {@Override C10>public void Run() {System.out.println ("This is a thread implemented with an internal class");}}; new Thread (runnable). Start ();}}             
Third, method reference

is actually a simplified notation for lambda expressions. The referenced method is actually the method body implementation of the lambda expression, the syntax is very simple, the left is a container (can be the class name, the instance name), the middle is "::", the right is the corresponding method name. As shown below:

ObjectReference::methodName

Reference format for general methods:

    1. If it is a static method, it is classname::methodname. As Object:: Equals
    2. If it is an instance method, it is instance::methodname. such as Object Obj=new object (); obj::equals;
    3. constructor. It's classname::new.
package com.yztcedu.lambdademo_01;< Span class= "Hljs-keyword" >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 (            

As you can see, the DoSomething method is the implementation of the lambda expression, and the advantage is that if you feel that the lambda method is very long and affects the readability of the code, the method reference is a workaround.

Four, the default method---interface improvement

Simply put, the interface can have an implementation method, and do not need to implement the class to implement its methods. Just precede the method name with a default keyword.

package com.yztcedu.lambdademo_01; @FunctionalInterface public  Interface a {void call ()  default void fun  () {System.out.println ( "I am the code in the default method 1 of the Interface");} default void fun2 () {System.out.println (              

Why do we have this feature? First, the previous interface is a double-edged sword, and the advantage is that it is oriented toward abstraction rather than specific programming, and the drawback is that when you need to modify the interface, you need to modify all of the classes that implement the interface, and the current Java 8 Collection framework does not have a foreach method. The usual solution is to add new methods and implementations to the relevant interfaces in the JDK. However, for a released version, there is no way to add a new method to the interface without affecting the existing implementation. So introduce the default method. Their purpose is to make interfaces without introducing incompatible development with existing implementations.

The difference between an interface and an abstract class in Java8

form the same point:
1. are abstract types;
2. All can have the implementation method (previous interface does not);
3. All methods can be implemented without implementing the class or the successor, (not previously, the default method in the interface now does not require implementation)
Different points
1. Abstract classes cannot be inherited in multiple ways, interfaces can (either multiple-type inheritance or multiple-behavior inheritance);
2. Abstract classes and interfaces reflect a different design concept. In fact, the abstract class represents the "is-a" relationship, the interface represents the "like-a" relationship;
3. The variable defined in the interface is the public static final type by default, and must be given its initial value, so the implementation class cannot be redefined or changed, and the variable in the abstract class defaults to the default type, and its value can be redefined in the subclass or re-assigned.

Summary: The default method gives us the convenience of modifying the interface without destroying the structure of the original implementation class, and the current collection framework for Java 8 has been heavily used to improve the default method, providing us with a smooth transition experience when we finally start using the Java 8 lambdas expression. Perhaps in the future we will see more of the default methods in the API design application.

V. Improved collection framework with Lambda 5.1 internal iterations in the set
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 (), "Zhang San"), and users.  Add (new User ( "John Doe"), and users.  Add (New user, "Harry"); Users.foreach (user user), System.out.  println (User.getage ()));}}                 
5.2 Stream API

The stream is simply a stream of data and has no data structure, so he can no longer traverse it once (this is something to be aware of when programming, not like collection, how many times there are data in it), and its source could be collection, array, Io and so on.

The flow function is to provide an operational big data interface that makes data manipulation easier and faster. It has the methods of filtering, mapping and reducing all kinds of methods, such as the intermediate method and the terminal method, the "flow" abstraction is inherently persistent, and the intermediate method always returns the stream, so if we want to get the final result, we must use the end operation to collect the final result of the stream. The distinction between these two methods is to look at his return value, if the stream is an intermediate method, otherwise it is the endpoint method.

Filter

Implementing filtering in the data flow is the most natural operation we can think of first. The stream interface exposes a filter method that accepts a predicate implementation that represents an operation to use a lambda expression that defines the filter condition.

Import Java.util.stream.Stream;Publicclass Streamdemo {public static void main(string[] args) {list<user> users = new Ar Raylist<user> (), Users.add (new User ( "Zhang San")), Users.add (new User ( "John Doe")); Users.add (new User ( "Harry")); stream<user> stream = Users.stream (); Stream.filter (P-p.getage () > 20); //filter older than 20}}                  
Map

If we now filter some data, such as when converting objects. The map operation allows us to perform a Function implementation (Function<t,r> 's generic t,r, which represents the execution of input and execution results), which accepts the arguments and returns.

Package com.yztcedu.lambdademo_01;Import java.util.ArrayList;Import java.util.List;Import Java.util.stream.Stream;public class Streamdemo {PublicStaticvoid Main (String[] args) {list<user> users =new Arraylist<user> (); users. Add (new User (), "Zhang San"), and users.  Add (new User ( "John Doe"), and users.  Add (new User ( "Harry")); stream<user> stream = Users.stream (); //All user objects older than 20 years old are converted to string 50 objects. Now there are only string objects in the stream. Stream. filter (user user), user.getage () > .  Map (user user), {return ';            }}} 
Count

The Count method is the end of a stream method that allows the results of the stream to be finally counted, returning a long

Package com.yztcedu.lambdademo_01;Import java.util.ArrayList;Import java.util.List;Import Java.util.stream.Collector;Import Java.util.stream.Stream;PublicClassStreamdemo {PublicStaticvoid main (String[] args) {List< user> users = new arraylist<user> (); Users.add (new User (20,  "Zhang San"); Users.add (new User (22,  "John Doe"); Users.add (new User (10,  "Harry")); stream<user> stream = Users.stream (); long count = stream.filter (user user), user.getage () >= return //returns the number of elements in the stream. System.out.println (count);}}              

Java-->lambda expression

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.