Java 8 new features: Lambda tutorial

Source: Internet
Author: User


What is Lambda?

Lambda is a new feature added to java's jdk. It illustrates java's support for other languages and absorbing advanced methods from other languages. Lambda expressions provide type references, method references, and default methods in java.

If Lambda is explained in Wikipedia, it will not be translated to retain the original taste (let's take a look at your understanding and have different opinions. You are welcome to discuss it)
Lambda (programming), a function (or a subroutine) defined, and possibly called, without being bound to an identifier
Lambda expression in Lambda calculus, a formal system in mathematical logic and computer science for expressing computation by way of variable binding and substitution
From: http://medianetwork.oracle.com/video/player/3373491280001


2. Example

Import java. util. arrayList; import java. util. collections; import java. util. comparator; import java. util. list; public class detail {public static void main (String [] args) {List ocuppys1 = new ArrayList (); ocuppys1.add ("bussinessman"); ocuppys1.add ("doctor "); ocuppys1.add ("teacher"); ocuppys1.add ("programer"); ocuppys1.add ("stuedent"); List ocuppys2 = new ArrayList (); ocuppys2.add Inessman "); role (" doctor "); ocuppys2.add (" teacher "); ocuppys2.add (" programer "); ocuppys2.add (" stuedent "); LambdaExpresstionTouris leTouris = new feature (); system. out. println ("use java 7 sort:"); System. out. println ("before:" + ocuppys1); leTouris. sortByJava7 (ocuppys1); System. out. println ("before:" + ocuppys1); System. out. println ("use java 8 sort:"); System. out. println ("before :" + Ocuppys2); leTouris. sortByJava8 (ocuppys2); System. out. println ("before:" + ocuppys2);} // use the original JAVA 7 sorting method private void sortByJava7 (List listStr) {Collections. sort (listStr, new Comparator () {public int compare (String s1, String s2) {return s1.compareTo (s2 );}});} // sort private void sortByJava8 (List listStr) {Collections. sort (listStr, (s1, s2)-> s1.compareTo (s2);} conclusion 1. Lambda is a function. 2. Function interface 3 used by the new API defined by Java 8, default function method 4, which can be used to reference the method 5, this article describes how to use its sorting function to implement the sorting lambda application. First, I will give an example and then analyze it in depth. Example: namespace: demonstrate lambda {public class Person {public string Name {get; set;} public int Age {get; set ;}} class Program {public static List PersonsList () {List persons = new List (); for (int I = 0; I <7; I ++) {Person p = new Person () {Name = I + "son", Age = 8-I,}; persons. add (p) ;}return persons;} static void Main (string [] args) {List persons = PersonsList (); persons = persons. where (p => p. age> 6 ). toList (); // set of all persons whose Age> 6: Person per = persons. singleOrDefault (p => p. age = 1); // A single people class of Age = 1 persons = persons. where (p => p. name. contains ("son ")). toList (); // A set of all names containing the son's Person }}}




After reading the example above, I believe you can see that it is indeed a sweet date. Let's take a look at it (p => p. age> 6 ..

First, let's look at the delegation.

// Subscribe to the supermarket
Delegate int GuangChaoshi (int );
Static void Main (string [] args)
{
GuangChaoshi gwl = JieZhang;
Console. WriteLine (gwl (10) + ""); // Print 20, delegated application
Console. ReadKey ();
}

// Checkout
Public static int JieZhang (int)
{
Return a + 10;
}


Let's look at the expression.

// Subscribe to the supermarket
Delegate int GuangChaoshi (int );
Static void Main (string [] args)
{          
// GuangChaoshi gwl = JieZhang;
GuangChaoshi gwl = p => p + 10;
Console. WriteLine (gwl (10) + ""); // Print 20. Apply the expression
Console. ReadKey ();
}        

The two pieces of code of the delegate and expression can be seen: In fact, p in the expression (p => p + 10;) represents the parameters in the delegate method, the p + 10 on the right of the expression symbol is the return result in the delegate method. Let's take a detour.

The following two more complex understandings are given.

1. Multi-parameter

// Subscribe to the supermarket
Delegate int GuangChaoshi (int a, int B );
Static void Main (string [] args)
{            
GuangChaoshi gwl = (p, z) => z-(p + 10 );
Console. WriteLine (gwl (10,100) + ""); // Print 80, z corresponds to parameter B, p corresponds to parameter
Console. ReadKey ();
}



2. Complicated lambda subject operations

///// Delegate to the supermarket ///// cost /// pay // change the value of delegate int GuangChaoshi (int a, int B ); static void Main (string [] args) {GuangChaoshi gwl = (p, z) => {int zuidixiaofei = 10; if (p <zuidixiaofei) {return 100 ;} else {return z-p-10 ;}}; Console. writeLine (gwl (10,100) + ""); // Print 80. z corresponds to parameter B and parameter p corresponds to parameter a Console. readKey ();}




For the above examples, I will introduce the FunDelegate.
FuncDelegate

T is a parameter type, which is a generic type delegate and is easy to use.

Example 1

Static void Main (string [] args) {Func gwl = p => p + 10 + "-- return Type: string"; Console. writeLine (gwl (10) + ""); // Print '20 -- return type: String', z corresponds to parameter B, p corresponds to parameter a Console. readKey ();}


Note: We can see that p here is an int type parameter, but the lambda body returns a string type.

Another example

Static void Main (string [] args) {Func gwl = (p, j) =>{ if (p + j = 10) {return true ;}return false ;}; console. writeLine (gwl (5, 5) + ""); // Print 'true', z corresponds to parameter B, p corresponds to parameter a Console. readKey ();}


Note: From this example, we can see that p is of the int type, j is of the int type, and the return value is of the bool type.

After reading the above two examples, I believe you should understand Func.Multiple parameters: the preceding parameter is the delegate method parameter, and the last parameter is the return type of the delegate method.
Lambda expression tree dynamic creation method

Static void Main (string [] args) {// I * j + w * x ParameterExpression a = Expression. parameter (typeof (int), "I"); // Create a Parameter in the Expression tree. As a node, ParameterExpression B = Expression is the lowest node. parameter (typeof (int), "j"); BinaryExpression be = Expression. multiply (a, B); // Here I * j, generate a node in the Expression tree, a higher level ParameterExpression c = Expression than the above node. parameter (typeof (int), "w"); ParameterExpression d = Expression. parameter (typeof (int), "x"); BinaryExpression be1 = Expression. multiply (c, d); BinaryExpression su = Expression. add (be, be1); // calculate two intermediate nodes and generate the final point Expression lambda = Expression. lambda (su, a, B, c, d); Console. writeLine (lambda + ""); // Print '(I, j, w, x) => (I * j) + (w * x ))', z corresponds to parameter B, and p corresponds to parameter a Func f = lambda. compile (); // Compile the lambda expression described in the expression tree into executable code and generate the delegate of the lambda expression. Console. writeLine (f (1, 1, 1, 1) + ""); // PRINT 2 Console. readKey ();}




The lambda expression tree of the previous code, as shown in the figure.



Related Article

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.