1. Implementing the Runnable threading case
Use (), {} Instead of anonymous classes:
Before Java 8:new Thread (New Runnable () { @Override public void Run () { System.out.println ("Before Java8" ); }}). Start ();//java 8 way:new Thread ((), System.out.println ("in java8!"). Start (); Output:too much code, for too little to DOLAMBDA expression rocks!!
You can implement lambda using the following syntax:
(params), expression
(params)-statement
(params), {statements}
If your method does not change any of the method parameters, such as just the output, then it can be abbreviated as follows:
() System.out.println ("Hello Lambda Expressions");
If your method accepts two method parameters, the following:
(int even, int odd), even + odd
2. Implement event handling
If you've ever done swing programming, you'll never forget to write event listener code. Use the lambda expression to write the code for a better event listener as shown below.
Before Java 8:jbutton show = new JButton ("show"); Show.addactionlistener (new ActionListener () { @Override Public void actionperformed (ActionEvent e) { System.out.println ("Without lambda expression is boring"); } });/ /Java 8 Way:show.addActionListener ((e), { System.out.println ("Action!! Lambda Expressions Rocks ");});
In Java 8, you can use a lambda expression to replace an ugly anonymous class.
3. Iterating through the list collection using a lambda expression
"Stream API", "Date and Time API"); for (String feature:features) { System.out.println (feature);} In Java 8:list features = Arrays.aslist ("Lambdas", "Default Method", "Stream API",
"Date and Time API"); Features.foreach (n-System.out.println (n));//Even better use Method reference feature of Java 8 Method reference is denoted by:: (double colon) operator//looks similar to score resolution operator of C++FEATURES.F Oreach (System.out::p rintln); Output:lambdasdefault Methodstream apidate and Time API
The method reference is using two colons:: this operation symbol.
4. Using lambda expressions and function interfaces
To support functional programming, Java 8 joins a new package, java.util.function, which has an interface java.util.function.Predicate that supports lambda function programming:
public static void Main (args[]) {List languages = arrays.aslist ("Java", "Scala", "C + +", "Haskell", "Lisp"); System.out.println ("Languages which starts with J:"); Filter (languages, (str)->str.startswith ("J")); System.out.println ("Languages which ends with a"); Filter (languages, (str)->str.endswith ("a")); System.out.println ("Print All Languages:"); Filter (languages, (str)->true); System.out.println ("Print No Language:"); Filter (languages, (str)->false); System.out.println ("Print language whose length greater than 4:"); Filter (languages, (str)->str.length () > 4);} public static void filter (List names, predicate condition) {for (String name:names) {if (Condition.test (name)) {SYSTEM.OUT.PRINTLN (name + ""); }}}}output:languages which starts with j:javalanguages which ends with Ajavascalaprint all languages:javascalac++h Askelllispprint No language:P rint language whose length greater than 4:scalahaskell//even better pubLic static void filter (List names, predicate condition) {Names.stream (). Filter ((name) (Condition.test (name))
. ForEach (name), {System.out.println (name + ""); }); }
You can see that the filter method from the stream API accepts the predicate parameter, allowing you to test multiple conditions.
5. A complex combination
predicateUse
Java.util.function.Predicate provides and (), or (), and XOR () can perform logical operations, for example, in order to get a string of 4 lengths that begin with "J":
We can even combine predicate using and (), or () and XOR () logical functions//For example to find names, which starts With J and four letters long, you//can pass combination of the predicate predicate<string> startswithj = (n) N.startswith ("J"); predicate<string> Fourletterlong = (n), n.length () = = 4; Names.stream () . Filter (startswithj. and (Fourletterlong)) . ForEach ((n), System.out.print ("\nname, which starts with
' J ' and four letter long are: ' + n ');
Which startswithj. and (Fourletterlong) is an operation that uses and logic.
6. Using lambda for map and Reduce
The most popular function programming concept is map, which allows you to change your object, in this case, we will change the Costbeforeteax collection of each element to add a certain value, we transfer the lambda expression x-x*x to the map () method, This is applied to all elements in the stream. We then use ForEach () to print out the elements of this collection.
Applying 12% VAT on each purchase//without lambda expressions:list costbeforetax = arrays.aslist (100, 200, 300, 400, 5 (Integer cost:costbeforetax) {Double Price = Cost +. 12*cost; SYSTEM.OUT.PRINTLN (price);} With Lambda expression:list Costbeforetax = arrays.aslist (+, +, +, +), Costbeforetax.stream (). Map (cost)- > Cost +. 12*cost)
. ForEach (System.out::p rintln); Output112.0224.0336.0448.0560.0112.0224.0336.0448.0560.0
Reduce () is the combination of all the values in the collection into one, reduce similar to sum () in the SQL statement, AVG (), or count (),
Applying 12% VAT on all purchase//old way:list Costbeforetax = arrays.aslist (+, Max, Mon, max);d ouble total = 0;for (Integer cost:costbeforetax) {Double price = Cost +. 12*cost; System.out.println ("total:" + all);//New Way:list Costbeforetax = arrays.aslist (+, +, +, +);d ouble bill = Costbeforetax.stream (). Map (cost), Cost +. 12*cost)
. reduce (sum, cost)-sum + cost)
. get (); System.out.println ("Total:" + Bill); outputtotal:1680.0total:1680.0
7. By
filteringCreates a collection of string strings
Filtering is a common operation for large collection operations, and the stream provides a filter () method that accepts a predicate object, which means that you can transmit a lambda expression as a filter logic into this method:
Create a List with the String more than 2 characterslist<string> filtered = Strlist.stream (). Filter (X-X.length ( ) > 2)
Strlist, filtered); Output:original list: [ABC, BCD, DEFG, JK], filtered list: [ABC, BCD, DEFG]
8. Apply a function to each element in the collection
We often need to apply certain functions to the elements in the collection, such as multiplying or dividing each element in the table by one value, and so on.
Convert String to uppercase and join them using comalist<string> G7 = Arrays.aslist ("USA", "Japan", "France", "Ge Rmany ", " Italy "," U.K. "," Canada "); String g7countries = G7.stream (). Map (x, X.touppercase ())
. Collect (Collectors.joining (",")); System.out.println (g7countries); Output:usa, JAPAN, FRANCE, Germany, ITALY, U.K, CANADA
The above is to convert the string to uppercase, and then use commas to string together.
9. Create a sub-list by copying different values
Use the distinct () method of stream to filter repeating elements in the collection.
Create List of square of all distinct numberslist<integer> numbers = arrays.aslist (9, 10, 3, 4, 7, 3, 4); list<integer> distinct = Numbers.stream (). Map (i*i). DISTINCT ()
. Collect (Collectors.tolist ()); System.out.printf ("Original List:%s, Square without duplicates:
%s%n ", numbers, distinct); Output:original List: [9, 10, 3, 4, 7, 3, 4],
Duplicates: [81, 100, 9, 16, 49]
10. Calculate the maximum, minimum, sum, and average values of the elements in the list
Get count, Min, Max, sum, and average for numberslist<integer> primes = arrays.aslist (2, 3, 5, 7, 11, 13, 17, 19, Intsummarystatistics stats = Primes.stream (). Maptoint ((x), X)
. Summarystatistics (); System.out.println ("highest prime number in List:" + Stats.getmax ()); System.out.println ("Lowest prime number in List:" + stats.getmin ()); System.out.println ("Sum of all prime numbers:" + stats.getsum ()); System.out.println ("Average of all primes numbers:" + stats.getaverage ()); output:highest prime number in List:29lowes T prime number in List:2sum of all primes numbers:129average of all prime numbers:12.9
"Go" Java 80 lambda expression cases