Lambda expressions are a new feature of Java 8 that can replace an interface implementation with only one function, leaving anonymous inner classes, and the code looks more concise and understandable. Lambda expressions also promote the iteration, traversal, and filtering of data for a collection. So how do you use lambda expressions in Android Studio?
The JDK used for the project will be JDK 8 or later
Modify the Build.gradle file to enable Jack and set sourcecompatibility,targetcompatibility to JDK 8
defaultconfig { ... jackoptions { enabled= true } } compileoptions {javaversion. Version_1_8 targetcompatibility javaversion. Version_1_8
You can then use lambda expressions happily in your project, and you'll feel the following:
Public classTestactivityextendsbaseactivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (r.layout.test); Findviewbyid (R.id.button1). Setonclicklistener (View-OnButton1 ()); Findviewbyid (R.id.button2). Setonclicklistener (View-OnButton2 ()); } Public voidOnButton1 () {Runnable Runnable= () Toast.maketext ( This, "ABCD", Toast.length_short). Show (); Runnable.run (); } Public voidOnButton2 () {Observable.from (Arrays.aslist (1, 2, 3, 4, 5) . Filter (integer, integer% 2 = = 0). Map (integer--Integer *integer). Subscribeon (Schedulers.io ()). Observeon (Androidschedulers.mainthread ()) . Subscribe (Integer-Toast.maketext ( This, string.valueof (integer), toast.length_short). Show ()); }}
Using lambda expressions in Android Studio