Getting started with Java lambda expressions

Source: Internet
Author: User
Tags netbeans java se

Getting started with Java lambda expressionsTags: javajava8lambdastreamlambda expressions2014-04-27 21:17 80566 People read Comments ($) Collection report Classification:Java Fundamentals ($)Original link: Start Using Java Lambda Expressions

Download the sample program Examples.zip .
Original date: April 16, 2014

Translation Date: April 27, 2014
Translation staff: Anchor
Introduction

( Translator Note: While looking very advanced, the essence of lambda expression is just a " Grammar Sugar", the compiler infers and helps you transform the wrapper into regular code, so you can use less code to do the same thing. I suggest not to use, because this and some very high-level hacker write code, simple, difficult to understand, difficult to debug, maintenance personnel want to dozens.)
Lambda expressions are an important new feature in Java SE 8. Lambda expressions allow you to replace a functional interface with an expression. The lambda expression, like a method, provides a normal argument list and a body that uses these parameters (body, which can be an expression or a block of code).
The lambda expression also enhances the collection library. Java SE 8 adds 2 packages for bulk operation of collection data: The Java.util.function package and the Java.util.stream package. Stream is like an iterator (iterator), but many additional features are attached. In general, lambda expressions and streams are the biggest changes since the Java language added generics (generics) and annotations (annotation). In this article, we'll see the powerful examples of lambda expressions and streams in the simple to complex example.
Environment Preparation
If you do not have Java 8 installed, you should install it first to use lambda and stream (the translator suggests Virtual Machinesinstallation, test use). Tools and Ides like NetBeans and IntelliJ idea support Java 8 features, including lambda expressions, repeatable annotations, compact profiles, and other features.
Here are the download links for Java SE 8 and NetBeans IDE 8:
Java Platform (JDK 8): Download Java 8 from Oracle or download it with NetBeans IDE
NetBeans IDE 8: NetBeans IDE download from NetBeans website
The syntax of a lambda expression
Basic syntax:
(parameters), expression
Or
(parameters)->{statements;}

Here is a simple example of a Java lambda expression:
1. No parameters are required and the return value is 5 ()-5//2. Receives a parameter (numeric type) that returns twice times its value x-2 * x//3. Accept 2 parameters (numbers) and return their difference (x, y), x–y//4. Receives 2 integers of type int, returning their and (int x, int y) x + y//5. Accepts a string object and prints in the console without returning any value (looks like a return void) (string s), System.out.print (s)
Basic Lambda Example
Now that we know what a lambda expression is, let's start with some basic examples. In this section, we'll see how lambda expressions affect the way we encode. Given a player list, programmers can use the For statement ("for Loop") to Traverse, in Java SE 8 can be converted to another form:
string[] ATP = {"Rafael Nadal", "Novak Djokovic",       "Stanislas Wawrinka",       "David Ferrer", "Roger Federer",       " Andy Murray "," Tomas Berdych ",       " Juan Martin Del Potro "}; List<string> players =  arrays.aslist (ATP);//previous loop mode for (String player:players) {     System.out.print ( Player + ";");} Use lambda expressions and function actions (functional operation) Players.foreach ((player)-System.out.print (player + ";")); Use the double colon operator (double colon operator) Players.foreach (system.out::p rintln) in Java 8;
As you can see, a lambda expression reduces our code to one line. Another example is in a graphical user interface program in which an anonymous class can be replaced with a lambda expression. Similarly, you can use this when implementing the Runnable interface:
Use anonymous inner class btn.setonaction (new Eventhandler<actionevent> () {          @Override public          void handle (ActionEvent Event) {              System.out.println ("Hello world!");           }    );//or Use lambda expressionbtn.setonaction (event- System.out.println ("Hello world!"));
The following is an example of using Lambdas to implement the Runnable interface:
1.1 Use the anonymous inner class new Thread (new Runnable () {    @Override public    void Run () {        System.out.println ("Hello world!");    }}). Start ();//1.2 Use lambda expressionnew Thread ((), System.out.println ("Hello world!"). Start ();//2.1 Use Anonymous inner class Runnable Race1 = new Runnable () {    @Override public    void Run () {        System.out.println (" Hello world! ");    }};/ /2.2 using lambda expressionrunnable Race2 = (), System.out.println ("Hello world!"); Call the Run method directly (no new thread is opened!) Race1.run (); Race2.run ();

Runnable lambda expression, using block format, converts five lines of code into single-line statements. Next, we'll use Lambdas to sort the collection in the next section.
sorting collections using Lambdas
In Java, the Comparator class is used to sort the collection. In the following example, we will follow the player's name, surname, name length, and the last letter. As in the previous example, the anonymous inner class is used first to sort, and then the lambda expression is used to refine our code.
In the first example, we'll sort the list by name. Using the old way, the code looks like this:
String[] players = {"Rafael Nadal", "Novak Djokovic",     "Stanislas Wawrinka", "David Ferrer",    "Roger Federer", "and Y Murray ",    " Tomas Berdych "," Juan Martin Del Potro ",    " Richard Gasquet "," John Isner "};//1.1 Sort PL by name using anonymous inner class Ayersarrays.sort (Players, new comparator<string> () {    @Override public    int Compare (string s1, string s2) {        return (S1.compareto (S2));}    );
With Lambdas, you can implement the same functionality with the following code:
1.2 Using lambda expression to sort playerscomparator<string> Sortbyname = (string s1, String s2), S1.compareto (S2) ); Arrays.sort (players, sortbyname);//1.3 can also be used as follows: Arrays.sort (players, (string s1, string s2)--(S1.compareto (S2))) ;

The other sort is shown below. As in the example above, the code implements comparator through anonymous inner classes and some lambda expressions, respectively:
1.1 Use the anonymous inner class according to surname Sort Playersarrays.sort (players, new comparator<string> () {@Override public int compar    E (string s1, string s2) {return (S1.substring (S1.indexof ("")). CompareTo (S2.substring (""))); }});//1.2 uses lambda expression ordering, according to surnamecomparator<string> sortbysurname = (string s1, String s2), s 1.substring (S1.indexof ("")). CompareTo (S2.substring (S2.indexof (""))); Arrays.sort (players, sortbysurname);//1.3 or so, doubt the original is wrong, the brackets are many ... Arrays.sort (Players, (string s1, String s2), s1.substring (S1.indexof (")"). CompareTo (S2.substring (s2.indexof (" ")) ) )     );/ /2.1 Use Anonymous inner class based on name lenght sort Playersarrays.sort (players, new comparator<string> () {@Override public int com    Pare (string s1, string s2) {return (S1.length ()-s2.length ()); }});//2.2 Using lambda expression ordering, according to name lenghtcomparator<string> sortbynamelenght = (string s1, string s2) (S1.length ()-s2.length ()); Arrays.sort(players, sortbynamelenght);//2.3 or Thisarrays.sort (players, (string s1, String s2), (S1.length ()-s2.length ()); /3.1 Use Anonymous inner class to sort players, according to the last letter Arrays.sort (players, new comparator<string> () {@Override public int compare (    String s1, string s2) {return (S1.charat (S1.length ()-1)-S2.charat (S2.length ()-1));         }});//3.2 Using lambda expression sorting, according to the last letter comparator<string> Sortbylastletter = (string s1, string s2) (S1.charat (S1.length ()-1)-S2.charat (S2.length ()-1)); Arrays.sort (players, sortbylastletter);//3.3 or Thisarrays.sort (players, (string s1, String s2), (S1.charat ( S1.length ()-1)-S2.charat (S2.length ()-1));
That's it, simple and intuitive. In the next section, we'll explore the capabilities of more lambdas and combine them with stream.
using lambdas and streams
Stream is a wrapper over a collection, usually used with lambda. Using Lambdas can support many operations, such as map, filter, limit, sorted, count, Min, max, sum, collect, and so on. Similarly, Stream uses Lazy Arithmetic, they don't really read all the data, and a method like GetFirst () ends the chain syntax. In the following example, we will explore what lambdas and streams can do. We create a person class and use this class to add some data to the list, which will be used for further flow operations. The person is just a simple Pojo class:
public class Person {private string firstName, LastName, job, Gender;private int. salary, Age;public person (String Firstnam E, string lastName, String job,                string gender, int age, int salary)       {          this.firstname = firstName;          This.lastname = LastName;          This.gender = gender;          This.age = age;          This.job = job;          This.salary = salary;} Getter and Setter//...}
Next, we will create two lists, all of which are used to store the person object:
list<person> javaprogrammers = new Arraylist<person> () {{Add (new person ("Elsdon", "Jaycob", "Java Progra    Mmer "," male ", 43, 2000));    Add (New Person ("Tamsen", "Brittany", "Java programmer", "female", 23, 1500));    Add (New Person ("Floyd", "Donny", "Java programmer", "male", 33, 1800));    Add (New Person ("Sindy", "Jonie", "Java programmer", "female", 32, 1600));    Add (New Person ("Vere", "Hervey", "Java programmer", "male", 22, 1200));    Add (New Person ("Maude", "Jaimie", "Java programmer", "female", 27, 1900));    Add (New Person ("Shawn", "Randall", "Java programmer", "male", 30, 2300));    Add (New person ("Jayden", "Corrina", "Java programmer", "female", 35, 1700));    Add (New Person ("Palmer", "Dene", "Java programmer", "male", 33, 2000));  Add (New Person ("Addison", "Pam", "Java programmer", "female", 34, 1300)); }}; list<person> phpprogrammers = new Arraylist<person> () {{Add (new person ("Jarrod", "Pace", "PHP programmer    "," male ", 34, 1550)); AddNew Person ("Clarette", "Cicely", "PHP programmer", "female", 23, 1200));    Add (New Person ("Victor", "Channing", "PHP programmer", "male", 32, 1600));    Add (New Person ("Tori", "Sheryl", "PHP programmer", "female", 21, 1000));    Add (New Person ("Osborne", "Shad", "PHP programmer", "male", 32, 1100));    Add (New Person ("Rosalind", "Layla", "PHP programmer", "female", 25, 1300));    Add (New Person ("Fraser", "Hewie", "PHP programmer", "male", 36, 1100));    Add (New Person ("Quinn", "Tamara", "PHP programmer", "female", 21, 1000));    Add (New Person ("Alvin", "Lance", "PHP programmer", "male", 38, 1600));  Add (New Person ("Evonne", "Shari", "PHP programmer", "female", 40, 1800)); }};
Now we iterate through the above list using the Foreach method:
System.out.println ("All Programmer's Name:"); Javaprogrammers.foreach ((P), System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ()));p Hpprogrammers.foreach ((p), System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ()));
We also use the Foreach method to increase the programmer's salary by 5%:
System.out.println ("Give the programmer a raise of 5%:"); consumer<person> giveraise = e-E.setsalary (E.getsalary ()/5 + e.getsalary ()); Javaprogrammers.foreach (g iveraise);p Hpprogrammers.foreach (giveraise);
Another useful method is filter filters (), which let us show PHP programmers with a monthly salary of more than $1400:
System.out.println ("Below is the PHP programmer with a monthly salary of more than $1,400:") Phpprogrammers.stream ()          . Filter ((P), (P.getsalary () > 1400) )          . ForEach ((p)-System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ()));
We can also define filters and then reuse them to do other things:
Definition filterspredicate<person> agefilter = (p), (P.getage () > 25); predicate<person> salaryfilter = (p), (P.getsalary () > 1400); predicate<person> genderfilter = (p) ("Female". Equals (P.getgender ())); System.out.println ("Below is a female PHP programmer older than 24 years with a monthly salary above $1,400:");p Hpprogrammers.stream ()          . Filter (Agefilter)          . Filter (Salaryfilter)          . Filter (Genderfilter)          . ForEach ((P), System.out.printf ("%s%s;", P.getfirstname () , P.getlastname ()));//Reuse filtersSystem.out.println ("women older than 24 years old Java programmers:"); Javaprogrammers.stream ()          . Filter (Agefilter)          . Filter (Genderfilter)          . ForEach ((P), System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ()));
You can limit the number of result sets by using the Limit method:
System.out.println ("First 3 Java Programmers:"); Javaprogrammers.stream ()          . Limit (3)          . ForEach ((p) System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ())); System.out.println ("first 3 female Java programmers:"); Javaprogrammers.stream ()          . Filter (Genderfilter)          . Limit (3 )          . ForEach ((p)-System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ()));
Sort of? Can we handle it in the stream? The answer is yes. In the example below, we will sort the Java programmer by name and salary, put it in a list, and then display the listing:
System.out.println ("Sort by name and show Top 5 Java Programmers:"); list<person> sortedjavaprogrammers = javaprogrammers          . Stream ()          . Sorted ((p, p2), P.getfirstname () . CompareTo (P2.getfirstname ()))          . Limit (5)          . Collect (ToList ()); Sortedjavaprogrammers.foreach (P) System.out.printf ("%s%s; %n ", P.getfirstname (), P.getlastname ())); System.out.println ("Sort Java programmers by salary:"); sortedjavaprogrammers = Javaprogrammers          . Stream ()          . Sorted (p, p2)-(P.getsalary ()-p2.getsalary ()). Collect (          toList ()); Sortedjavaprogrammers.foreach (P)- > System.out.printf ("%s%s; %n ", P.getfirstname (), P.getlastname ()));
If we are only interested in the lowest and highest salary, the Min and Max methods are the first/last faster than the sorting option:
System.out.println ("The lowest-paid Java programmer:"); Person pers = Javaprogrammers          . Stream ()          . Min ((P1, p2) (P1.getsalary ()-p2.getsalary ())          . Get () System.out.printf ("Name:%s%s; Salary: $%,d. ", Pers.getfirstname (), Pers.getlastname (), Pers.getsalary ()) System.out.println (" the highest-paid Java programmer: "); Person person = Javaprogrammers          . Stream ()          . Max ((p, P2)-(P.getsalary ()-p2.getsalary ()))          . Get () System.out.printf ("Name:%s%s; Salary: $%,d. ", Person.getfirstname (), Person.getlastname (), Person.getsalary ())
In the example above we have seen how the Collect method works. In conjunction with the map method, we can use the Collect method to place our result set into a string, a set, or a treeset:
SYSTEM.OUT.PRINTLN ("Stitching the first name of PHP programmers into a string:"); String phpdevelopers = phpprogrammers          . Stream ()          . Map (person::getfirstname)          . Collect (Joining (";"));// In the further operation can be used as token (token)   System.out.println ("store the first name of Java programmers to Set:"); set<string> javadevfirstname = javaprogrammers          . Stream ()          . Map (person::getfirstname)          . Collect ( Toset ()); System.out.println ("Store the first name of Java programmers to TreeSet:"); treeset<string> javadevlastname = javaprogrammers          . Stream ()          . Map (person::getlastname)          . Collect ( Tocollection (treeset::new));
The Streams can also be parallel (parallel). Examples are as follows:
System.out.println ("Calculates all money paid to Java programmers:"), int totalsalary = Javaprogrammers          . Parallelstream ()          . Maptoint (P-p.getsalary ())          . sum ();
We can use the Summarystatistics method to get various summary data for the elements in the stream. Next, we can access these methods, such as Getmax, Getmin, getsum or getaverage:
Count, Min, Max, sum, and average for numberslist<integer> numbers = arrays.aslist (1, 2, 3, 4, 5, 6, 7, 8, 9, 1 0); Intsummarystatistics stats = numbers          . Stream ()          . Maptoint ((x), X)          . Summarystatistics (); System.out.println ("The largest number in the list:" + Stats.getmax ()); System.out.println ("Smallest number in list:" + stats.getmin ()); System.out.println ("Sum of all numbers   
OK, that's it, hope you like it!
Summary
In this article, we learned the different ways to use lambda expressions, from basic examples to complex examples using lambdas and streams. In addition, we learned how to use lambda expressions with the comparator class to sort Java collections.

Getting started with Java lambda expressions

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.