Original link: Start Using Java Lambda Expressions
Download the sample program Examples.zip.
Introduction
(Translator Note: Although it looks very advanced, the essence of a lambda expression is just a "syntactic sugar", which is inferred by the compiler and helps you transform the code packaged as normal, so you can use less code to achieve the same function.) I suggest not to use, because this and some very advanced hackers write code, simple, difficult to understand, difficult to debug, maintenance staff want to dozens. A
lambda expression is an important new feature in Java SE 8. Lambda expressions allow you to use expressions instead of functional interfaces. A lambda expression, like a method, provides a normal list of arguments and a body that uses those arguments (the bodies, 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 operations on collection data: Java.util.function packages and Java.util.stream packages. Flow (stream) is like an iterator (iterator), but many additional features are attached. In general, lambda expressions and stream are the biggest changes since the Java language adds generics (generics) and annotations (annotation). In this article, we'll see the toughness of lambda expressions and stream from simple to complex examples.
Environment Preparation
If you have not installed Java 8, you should install it before you can use the lambda and stream (the translator recommends that you install it in a virtual machine, test it for use). Tools like NetBeans and IntelliJ idea and the IDE support Java 8 features, including lambda expressions, repeatable annotations, compact profiles, and other features.
Below are download links to Java SE 8 and NetBeans IDE 8:
Java Platform (JDK 8): Download Java 8 from Oracle, or download the
NetBeans IDE with the NetBeans IDE 8: Download the NetBeans IDE
syntax for lambda expressions
Basic Syntax:
(parameters)-> expression
or
(parameters) ; {statements;}
The following is a simple example of a Java lambda expression:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
1. No arguments required, the return value is 5
()-> 5
2. Receives a parameter (numeric type) that returns twice times the value of the
X-> 2 * x
3. Accept 2 parameters (numbers) and return their difference
(x, y)-> computes
4. Receives 2 int integers, returns their and
(int x, int y)-> x + y
5. Accepts a string object and prints it on the console without returning any values (looks like return void)
(String s)-> System.out.print (s)
The 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 how we encode. Assuming that there is a player list, programmers can use the For statement ("for Loop") to Traverse, in Java SE 8 can be converted to another form:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
string[] ATP = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka",
"David Ferrer", "Roger Federer",
"Andy Murray", "Tomas Berdych",
"Juan Martin Del Potro"};
List players = Arrays.aslist (ATP);
The previous cycle mode
for (String player:players) {
System.out.print (player + ";");
}
Using lambda expressions and function operations (functional operation)
Players.foreach (player)-> System.out.print (player + ";");
Using the double colon operator in Java 8 (double colon operator)
Players.foreach (System.out::p rintln);
As you can see, lambda expressions reduce our code to one line. Another example is that in a graphical user interface program, an anonymous class can be substituted with a lambda expression. Similarly, you can use this when implementing the Runnable interface:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Using anonymous inner classes
Btn.setonaction (New EventHandler () {
@Override
public void handle (ActionEvent event) {
System.out.println ("Hello world!");
}
});
or use lambda expression
Btn.setonaction (Event-> System.out.println ("Hello world!"));
The following is an example of using Lambdas to implement the Runnable interface:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
1.1 Using anonymous inner classes
New Thread (New Runnable () {
@Override
public void Run () {
System.out.println ("Hello world!");
}
). Start ();
1.2 Using lambda expression
New Thread (()-> System.out.println ("Hello world!"). Start ();
2.1 Using anonymous inner classes
Runnable Race1 = new Runnable () {
@Override
public void Run () {
System.out.println ("Hello world!");
}
};
2.2 Using lambda expression
Runnable Race2 = ()-> System.out.println ("Hello world!");
Call the Run method directly (no new threads open!)
Race1.run ();
Race2.run ();
Runnable lambda expression, using block format, to convert the five-element code into a single-line statement. Next, we'll sort the collection using Lambdas in the next section.
Using Lambdas to sort collections
In Java, the Comparator class is used to sort collections. In the following example, we will be based on 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 streamline our code.
In the first example, we'll sort the list by name. Using the old way, the code looks like this:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
String[] players = {"Rafael Nadal", "Novak Djokovic",
"Stanislas Wawrinka", "David Ferrer",
"Roger Federer", "Andy Murray",
"Tomas Berdych", "Juan Martin Del Potro",
"Richard Gasquet", "John Isner"};
1.1 Using anonymous inner classes to sort by name players
Arrays.sort (Players, new Comparator () {
@Override
public int Compare (string s1, string s2) {
Return (S1.compareto (S2));
}
});
With Lambdas, you can implement the same functionality in the following code:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
1.2 Using lambda expression to sort players
Comparator sortbyname = (string s1, string s2)-> (S1.compareto (S2));
Arrays.sort (players, sortbyname);
1.3 can also take the following form:
Arrays.sort (Players, (string s1, string s2)-> (S1.compareto (S2)));
The other sorts are shown below. As with the previous example, the code implements comparator by means of an anonymous inner class and some lambda expressions:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
1.1 Using anonymous inner classes to sort by surname players
Arrays.sort (Players, new Comparator () {
@Override
public int Compare (string s1, string s2) {
Return (s1.substring s1.indexof ("")). CompareTo (S2.substring (S2.indexof ("")));
}
});
1.2 Using lambda expression sort, according to surname
Comparator sortbysurname = (string s1, string s2)->
(S1.substring (S1.indexof ("")). CompareTo (S2.substring (S2.indexof ("")));
Arrays.sort (players, sortbysurname);
1.3 Or so, doubt the original person is wrong, parentheses a lot ...
Arrays.sort (Players, (string s1, string s2)->
(S1.substring (S1.indexof ("")). CompareTo (S2.substring (S2.indexof ("")))
);
2.1 Using anonymous inner classes to sort by name lenght players
Arrays.sort (Players, new Comparator () {
@Override
public int Compare (string s1, string s2) {
Return (S1.length ()-s2.length ());
}
});
2.2 Using lambda expression sorting, according to name lenght
Comparator sortbynamelenght = (string s1, string s2)-> (S1.length ()-s2.length ());
Arrays.sort (players, sortbynamelenght);
2.3 or this
Arrays.sort (Players, (string s1, string s2)-> (S1.length ()-s2.length ()));
3.1 Using anonymous inner class sort players, according to the last letter
Arrays.sort (Players, new Comparator () {
@Override
public int Compare (string s1, string s2) {
Return (S1.charat (S1.length ()-1)-S2.charat (S2.length ()-1));
}
});
3.2 Using a lambda expression sort, according to the last letter
Comparator Sortbylastletter =
(string s1, string s2)->
(S1.charat (S1.length ()-1)-S2.charat (S2.length ()-1));
Arrays.sort (players, Sortbylastletter);
3.3 or this
Arrays.sort (Players, (string s1, string s2)-> (S1.charat (S1.length ()-1)-S2.charat (S2.length ()-1));
That's it, it's simple and intuitive. In the next section, we'll explore more lambdas capabilities and use them in conjunction with stream.
Using Lambdas and Streams
A stream is a wrapper over a collection, usually used with a lambda. Using Lambdas can support many operations, such as map, filter, limit, sorted, count, Min, max, sum, collect, and so on. Similarly, the stream uses lazy arithmetic, they don't really read all the data, and a method like GetFirst () ends the chain syntax. In the next example, we will explore what lambdas and streams can do. We created a person class and used this class to add some data to the list, which will be used for further flow operations. Person is just a simple Pojo class:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
public class Person {
Private String FirstName, lastName, job, gender;
private int salary, age;
Public person (string firstName, 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'll create two lists, all for the person object:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
List javaprogrammers = new ArrayList () {
{
Add (New Person ("Elsdon", "Jaycob", "Java programmer", "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 phpprogrammers = new ArrayList () {
{
Add (New Person ("Jarrod", "Pace", "PHP programmer", "male", 34, 1550));
Add (New 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 use the Foreach method to iterate over the above list:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("Name of all programmers:");
Javaprogrammers.foreach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
Phpprogrammers.foreach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
We also use the Foreach method to increase the programmer's pay by 5%:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("Give the programmer a raise of 5%:");
Consumer giveraise = e-> e.setsalary (e.getsalary ()/MB * 5 + e.getsalary ());
Javaprogrammers.foreach (giveraise);
Phpprogrammers.foreach (giveraise);
Another useful method is filter filters (), which allows us to display a PHP programmer who earns more than 1400 dollars a month:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("Below is a monthly salary more than $1,400 PHP Programmer:")
Phpprogrammers.stream ()
. Filter ((p)-> (P.getsalary () > 1400))
. ForEach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
We can also define filters and reuse them to do other things:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
Define Filters
predicate agefilter = (p)-> (P.getage () > 25);
predicate salaryfilter = (p)-> (P.getsalary () > 1400);
predicate genderfilter = (p)-> ("Female". Equals (P.getgender ()));
System.out.println ("Below is a female PHP programmer who is older than 24 and has a monthly salary above $1,400:");
Phpprogrammers.stream ()
. Filter (Agefilter)
. Filter (Salaryfilter)
. Filter (Genderfilter)
. ForEach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
Reusing filters
System.out.println ("Older than 24-year-old female 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:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("Front 3 Java Programmers:");
Javaprogrammers.stream ()
. Limit (3)
. ForEach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
System.out.println ("Front 3 female Java programmers:");
Javaprogrammers.stream ()
. Filter (Genderfilter)
. Limit (3)
. ForEach ((p)-> System.out.printf ("%s%s;", P.getfirstname (), P.getlastname ());
What sort? Can we handle it in the stream? The answer is yes. In the example below, we'll sort the Java programmers by name and salary, put them in a list, and then display the lists:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("sorted by name and displaying the first 5 Java programmers:");
List 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 according to 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, select the first/last one faster than the sort after the Min and Max methods:
[Plain] View plain copy on the code to see a piece of coding derived to my Code slice
SYSTEM.OUT.PRINTLN ("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. Combining the map method, we can use the Collect method to place our result set in a string, a set, or a treeset:
[Java] View plain copy on the code to see a piece of coding derived from my Code slice
System.out.println ("Concatenation of the PHP programmers's name into a string:");
String phpdevelopers = phpprogrammers
. Stream ()
. Map (Person::getfirstname)
. Collect (Joining (";")); Can be used as a marker in further operations (token)
System.out.println ("Store the Java programmers's name to Set:");
Set Javadevfirstname = javaprogrammers
. Stream ()
. Map (Person::getfirstname)
. Collect (Toset ());
System.out.println ("store the Java programmers's name to TreeSet:");
TreeSet javadevlastname = javaprogrammers
. Stream ()
. Map (person::getlastname)
. Collect (Tocollection ( Treeset::new)); The
Streams can also be parallel (parallel). The example is as follows:
[Java] View plain copy on the code to see the snippet derived from my Code slice
System.out.println ("Calculate all money paid to the Java programmers:");
int totalsalary = Javaprogrammers
. Parallelstream ()
. Maptoint (P-> p.getsalary ())
. sum ();
We can use the Summarystatistics method to get the various rollup data for the elements in the stream. Next, we can access these methods, such as Getmax, Getmin, Getsum, or getaverage:
[Java] View plain copy on the code to view the snippets derived to my Code
//Count, Min, Max, sum, and average for numbers
List numbers = arrays.aslist (1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Intsummarystatistics stats = numbers
. Stream ()
. Maptoint ((x)-> x)
. Summarystatistics ();
System.out.println ("the largest number in the list:" + Stats.getmax ());
System.out.println ("The smallest number in the list:" + stats.getmin ());
System.out.println ("Sum of all numbers:" + stats.getsum ());
System.out.println ("Average of all numbers:" + stats.getaverage ());
OK, that's it, I hope you like it!
Summary
In this article, we learned different ways to use lambda expressions, from basic examples to complex examples that use lambdas and streams. In addition, we learned how to sort the Java collection using lambda expressions and the comparator class.