JAVA8 LAMDBA Expression 003

Source: Internet
Author: User

Continue to LAMDBA. JAVA8 LAMDBA Expression 002 Describes the use of LAMDBA to sort the collection elements, this chapter uses the LAMDBA to filter the collection elements, the demo sample code inherits 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 of participation in the article}
As seen in 001, create a set merge to include several elements in the collection. Name. Scores. Now I want to filter the elements in the collection, for example, I want to get all the elements with a score greater than or equal to 5 put them in a collection 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 ());
Create a new collection in 002 to hold the element that meets the criteria, using stream because it includes easy-to-use filtering capabilities. The stream is generated from playerlist and then the filter function is called, and the filtering process uses the LAMDBA expression.

The LAMDBA expression passes a player object as a parameter and then filters based on the condition goals>=5. Assuming conformance then add this element to the newly created set.


Through the above study. We should have a deep impression of the LAMDBA expression, which declares a functional interface, which is simply an interface of an abstract method, and is implemented with a LAMDBA expression.

Or use the function<argument,return> definition. and implemented.

In a traditional Java class. There is also an interface that has only an abstract method. For example, create a new thread java.util the Runnable interface under the package, which only has a run abstract method. We now consider implementing the Runnable interface using LAMDBA expressions. and the traditional implementation of the comparison.

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 ();}}
Because 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 reference, so the list is a pair of empty parentheses ().
Runnable Assignment = () {expression or statements};

Assuming you've written javase interface or written Android code, you might know that when you click on a button, there is an anonymous inner class defined in the method, and the method is implemented to handle the button click Trigger action. Next we talk about how to use LAMDBA expressions instead of this cumbersome inner class implementation code.

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 Demo Example: We have defined a button to set the Click event for BUTTONBTN.

Setonaction, inside the button click action Processing.

Creating a new anonymous class, and then implementing the handle method in it, is complicated, and the next demo example shows that we can use LAMDBA to easily get things done.

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 very easy to 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 little attention. Suppose Multiplynum is defined in main, not a local variable in a class. There will be an error here, and the variable in the LAMDBA within a closed range must be final or final. You cannot change the value of it.

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, such as the following:

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;}
Next, add LAMDBA's implementation and test it!

public class Passinglambdafunctions {public Double calculate (function<list< Double> double> f1,double[] args) {//See 005, omit}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));}} 
No matter what type of functionality you can use the LAMDBA implementation and then pass it on to different objects. This will improve the reusability & maintainability of the code. Lamdba is talking about this. Assuming that these are not enough to meet your needs, you can go to the official website to find more detailed code. Or search for what you want.

PS: This demo sample is quoted from Josh Juneau Java 8 Recipes, 2nd Edition
Mission completed!


O (∩_∩) o~

JAVA8 LAMDBA Expression 003

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.