Java8 new feature-lambda expression-basic knowledge

Source: Internet
Author: User

A Lambda expression is an unnamed block of code (or an unnamed function) with a list of formal parameters and a
Body.

Lambda expressions in Java8 are different from C #, using the

eg

//Takes an int parameter and returns the parameter value incremented by 1(intx) x + 1//Takes parameters and returns their sum(intXintY)-X +y//Takes parameters and returns the maximum of the(intXintY) {     intmax = x > y?x:y; returnMax;}//Takes no parameters and returns void() { }//Takes No parameters and returns a string "OK"(), "OK"//Takes a String parameter and prints it on the standard output(String msg),{System.out.println (msg);}//Takes a parameter and prints it on the standard outputMSG-System.out.println (msg)//Takes a String parameter and returns its length(String str), Str.length ()


Let's look at a simple example

Adder.java

 Package Corejava2.lambda; @FunctionalInterface  Public Interface Adder {    double Add ( double n2);} 

Joiner.java

 Package Corejava2.lambda; @FunctionalInterface  Public Interface Joiner {    string join (string s1, string s2);}

Targettypetest.java

 PackageCorejava2.lambda; Public classTargettypetest { Public Static voidMain (string[] args) {//creates an Adder using a lambda expressionAdder Adder = (x, y) x +y; //creates a Joiner using a lambda expressionJoiner Joiner = (x, y) x +y; //Adds Doubles        DoubleSUM1 = Adder.add (10.34, 89.11); //Adds ints        Doublesum2 = Adder.add (10, 89); //Joins StringsString str = joiner.join ("Hello", "Lambda"); System.out.println ("SUM1 =" +sum1); System.out.println ("sum2 =" +sum2); System.out.println ("str =" +str); }}

Operation Result:
SUM1 = 99.45
sum2 = 99.0
str = Hello Lambda

Java8 new feature-lambda expression-basic knowledge

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.