Continue to LAMDBA, the previous Java8 LAMDBA expression 002, using LAMDBA to sort the collection elements, this article describes using LAMDBA to filter the collection elements, the sample code follows the previous article:
001
public class Sortingplayer {public static void main (string[] args) {list<player> playerlist = new Arraylist<> ( ;p Layerlist.add ("Black", "White", 9));p Layerlist.add ("John", "Hello", 2);p Layerlist.add (new Player ("Machicel", "Jackson", 7));p Layerlist.add ("Ani", "Hessius", 4);p Layerlist.add ("New player", "Mark", " Towns ", 3));p Layerlist.add (New Player (" Huge "," Nana ", 6));}} Class player{//definition Reference Previous}
Create a set, as shown in 001, and add several elements to the collection. Name, score. Now we're going to filter the elements in the collection, like I'm going to get all the elements with a score greater than or equal to 5, put them in another set, and print out the number of elements that match the criteria.
002
/** * Specifying Filter Criteria on a Collection of Data */list<player> biggoals = new arraylist<> ();p Layerlis T.stream (). Filter (P, p.getgoals () >= 5). ForEach (element, Biggoals.add (element)); System.out.println ("Number of Players Matching Criteria:" + biggoals.size ());
A new collection of 002 is used to hold the eligible elements, using stream because it contains easy-to-use filtering capabilities. Based on the playerlist generated stream and then called the filter function above, the filtering process uses the LAMDBA expression. The LAMDBA expression passes a player object as a parameter and then filters according to the condition goals>=5, adding the element to the new collection if it matches.
Through the above study, we should have a deep impression of the LAMDBA expression, it declares a functional interface, that is, an interface with only an abstract method, and implemented with the LAMDBA expression. Or use function<argument,return> to define and implement. In traditional Java classes, there is also an interface with only one abstract method, such as a new runnable interface under a thread Java.util package, which has only one run abstract method. Now we consider implementing the Runnable interface using the LAMDBA expression and comparing it with the traditional implementation.
003
public class Runnablecompare {public static void main (string[] args) {Runnable oldrunnable = new Runnable () {@Overridepubl IC void Run () {int x = 5 * 3; SYSTEM.OUT.PRINTLN ("The variable using the old" equals: "+ x);}}; Runnable lambdarunnable = () {int x = 5 * 3; SYSTEM.OUT.PRINTLN ("The variable using the lambda equals:" + x);};o Ldrunnable.run (); Lambdarunnable.run ();}}
Since java.util.Runnable is a functional interface, boilerplate code such as interface implementations can be replaced with LAMDBA. The abstract method in runnable is no parameter, so the argument list is a pair of empty parentheses ().
Runnable Assignment = () {expression or statements};
If you've written a javase interface or written Android code, you might know that when you click a button, there is an anonymous inner class defined in the method, and the method is implemented to handle the action of the button click Trigger. Next we talk about how to replace this cumbersome inner class implementation code with LAMDBA expressions.
003
Import Javafx.event.actionevent;import Javafx.event.eventhandler;import Javafx.scene.control.button;public class replacinganonymousinnerclasses {public static void main (string[] args) {Button btn = new Button ();/** * Typical */btn. Setonaction (New eventhandler<actionevent> () {@Overridepublic void handle (ActionEvent e) {System.out.println (" Do something ... typical ");}); * * Lambda */btn.setonaction (E->{system.out.println ("Do something ... lambda");});}
003 Example: We have defined a button to set the Click event for the button btn. Setonaction, inside the button click operation Processing. Creating a new anonymous class, and then implementing the handle method in it, is very complex, and the next example sees that we can use LAMDBA to easily fix it.
The LAMDBA expression can also be used as a parameter in a method;
For example, I want to calculate a collection list<double> each element of the product, through the above learning we can easily write this function:
004
Import Java.util.arraylist;import Java.util.list;import Java.util.function.function;public class Test {private static Double multiplynum = 1d;public static void Main (string[] args) {function<list<double>, double> Multiply = Doublelist, {doublelist.stream (). ForEach (num, multiplynum *= num); return multiplynum;}; list<double> list = new arraylist<> (); List.add (12.3); List.add (25.6); List.add (38.4); Multiply.apply (list ); System.out.println (Multiplynum.intvalue ());}}
PS: The above uses the function to define the LAMDBA expression used to calculate the product of the collection elements, here is a note, if Multiplynum is defined in main, rather than in the local variables of the class, then here will be an error, The variable in the LAMDBA in a closed range must be final or final, and you cannot change its value.
OK, write the calculation method, we define a function to receive a LAMDBA expression, and the set of elements to be evaluated, and then return the result of the calculation, as follows:
005
Public Double Calculate (function<list<double>, double> f1,double[] args) {double returnvalue; list<double> varlist = new arraylist<> (); int idx = 0;while (idx < args.length) {Varlist.add (args[idx]); IDX ++;} returnvalue = f1.apply (varlist); return returnvalue;}
Then add the LAMDBA and test it!
public class Passinglambdafunctions {public Double calculate (function<list<double>, double> f1,double[] args) {//See 005, omitted here}public static void Main (string[] args) {Double x = 16.0;double y = 30.0;double z = 4.0; Function<list<double>, double> Volumecalc = List, {if (list.size () = = 3) {return List.get (0) * List.get (1 ) * List.get (2);} else {return double.valueof ("-1");}};D ouble[] argList = new Double[3];arglist[0] = x;arglist[1] = y;arglist[2] = Z; Function<list<double>, double> Areacalc = List, {if (list.size () = = 2) {return List.get (0) * List.get (1); } else {return double.valueof ("-1");}};D ouble[] ArgList2 = new Double[2];arglist2[0] = x;arglist2[1] = y; passinglambdafunctions P1 = new Passinglambdafunctions (); System.out.println ("The volume is:" + p1.calculate (Volumecalc, argList)); System.out.println ("The area is:" + p1.calculate (Areacalc, ArgList2));}}
Any type of functionality can be implemented using LAMDBA and then passed to different objects. This can improve the reusability & maintainability of the code more. Lamdba is talking about this. If you do not feel that these are not enough to meet your needs, you can go to the official website to find more detailed code, or search for the content you want.
PS: This example is quoted from Josh Juneau Java 8 Recipes, 2nd Edition
Mission completed!
O (∩_∩) o~
JAVA8 LAMDBA Expression 003