Java8 It has been released for some time , The changes in this release are relatively large , Many people associate this change with Java5 Compared to the upgrade of .Java8 One of the most important new features is lambda expression , Allows us to pass behavior to functions . think about it , stay Java8  Previously, we wanted to pass behavior into the function , The only option is anonymous inner classes .Java8 After release ,lambda Expressions will largely replace the use of anonymous inner classes , While simplifying code , It highlights that the most important part of the original anonymous inner class contains real logic code . Especially for students who do data , When used to using similar scala Functional programming languages like , Experience will be more profound . Now let's take a look Java8 in lambda Some common ways to write expressions .

lambda The parameter list and the return value type of the calling method in the body. , It should be consistent with the parameter list and return value type of the abstract method in the functional interface .

one , Override anonymous inner class

lambda Expressions are most often used to replace anonymous inner classes , realization Runnable Interface is a classic example of an anonymous inner class .lambda Expressions are quite powerful , use ()-> Can replace the entire anonymous inner class !

1, Code example
package javase.Lambda; import org.junit.Test; import java.util.Comparator;
import java.util.function.Consumer; import java.util.function.Function; import
java.util.function.Predicate; import java.util.function.Supplier; public class
Test1{ public static void main(String[] args) { Runnable runnable = new
Runnable() { @Override public void run() { System.out.println(" ordinary , Thread start "); } };
runnable.run(); test2(); test3(); test4(); test5(); } // No parameters , No return value public static
void test2() {
//“->” There is only one parenthesis on the left , Indicates no parameters , On the right is Lambda body ( It is equivalent to implementing the methods in the anonymous inner class ,( That is, an available interface implementation class .)) Runnable
runnable = ()->System.out.println("Lambda Expression mode , Thread start "); runnable.run(); }
// There is one parameter , And no return value public static void test3() { // this e The parameters of the method representing the implemented interface ,
Consumer<String> consumer = e->System.out.println("Lambda Expression mode ,"+e);
consumer.accept(" Incoming parameters "); } // There are more than two parameters , There is a return value , also Lambda There are multiple statements in the body public static void
test4() { //Lambda There are multiple statements in the body , Remember to enclose it in curly braces Comparator<Integer> com = (x, y) -> {
System.out.println(" Functional interface "); return Integer.compare(x, y); }; int compare =
com.compare(100, 244); System.out.println(" There are more than two parameters , There is a return value ,"+compare); } // if
Lambda There is only one statement in the body , return and Braces can be omitted public static void test5() { //Comparator
com = (x, y) -> Integer.compare(100, 244); System.out.println(" if Lambda
There is only one statement in the body , return and Braces can be omitted ,"+Integer.compare(100, 244)); } }
2, console output  

two ,Java8 Four built-in functional interfaces

If used lambda It's too troublesome to write an interface yourself , therefore Java They provided some interfaces :

1,Consumer Consumer interface :void accept(T t);
// There is one parameter , And no return value public static void test3() { // this e The parameters of the method representing the implemented interface ,
Consumer<String> consumer = e->System.out.println("Lambda Expression mode ,"+e);
consumer.accept(" Incoming parameters "); }
2,Supplier Supply type interface : T get();
package javase.Lambda; import java.util.ArrayList; import
java.util.function.Supplier; public class Test2 { public static void
main(String[] args) { ArrayList<Integer> res =
getNumList(10,()->(int)(Math.random()*100)); System.out.println(res); } public
static ArrayList<Integer> getNumList(int num, Supplier<Integer> sup){
ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < num; i++) {
Integer e = sup.get(); list.add(e); } return list; } }

3,Function Functional interface :R apply(T t);
package javase.Lambda; import java.util.function.Function; public class Test2
{ public static void main(String[] args) { String newStr =
strHandler("abc",(str)->str.toUpperCase()); System.out.println(newStr); newStr
= strHandler(" abc ",(str)->str.trim()); System.out.println(newStr); } public
static String strHandler(String str, Function<String,String>fun){ return
fun.apply(str); } }

4,Predicate Assertive interface :boolean test(T t);

Determine the length of some string arrays >2 String of :
package javase.Lambda; import java.util.ArrayList; import java.util.Arrays;
import java.util.List; import java.util.function.Predicate; public class Test2
{ public static void main(String[] args) { List<String> list =
Arrays.asList("hello","jiangshuying","lambda","www","ok","q"); List<String> ret
= filterStr(list,(str)->str.length()>2); System.out.println(ret); } public
static List<String> filterStr(List<String> list, Predicate<String> pre){
ArrayList<String> arrayList = new ArrayList<>(); for(String str:list){
if(pre.test(str)) { arrayList.add(str); } } return arrayList; } }

three , Method reference and constructor reference

requirement : Implement the parameter list and return value type of the abstract method , Must be consistent with the parameter list and return value type of the method referenced by the method !

Method reference : Using operators “::” Separate classes from methods .

object :: Instance method name
class :: Static method name
class :: Instance method name

for instance :
public static void test9(){ Comparator<Integer> comparator =
(x,y)->Integer.compare(x,y); Comparator<Integer> comparator1 =
Integer::compare; int compare = comparator.compare(1,2); int compare1 =
comparator1.compare(1,2); System.out.println("compare:"+compare);
System.out.println("compare1:"+compare1); }

four ,lambda Some common uses of expressions

1, use lambda Expression iterates over the collection
package javase.Lambda; import java.util.Arrays; import java.util.List; public
class Test3 { public static void main(String[] args) { List<String> list =
Arrays.asList("java","c#","javascript"); //before java8 for (String str:list){
System.out.println("before java8,"+str); } //after java8 list.forEach(x->
System.out.println("after java8,"+x)); } }

2, use lambda Expression implementation map

map Function is the most important method in functional programming .map The function of is to transform one object into another . In our example , Is through map Method will cost Increased 0,05 Times the size and then output .
package javase.Lambda; import java.util.Arrays; import java.util.List; public
class Test3 { public static void main(String[] args) { List<Double> list =
Arrays.asList(10.0,20.0,30.0); list.stream().map(x->x+x*0.05).forEach(x->
System.out.println(x)); } }

3, use lambda Expression implementation map And reduce

Now that I mentioned it map, How can we not mention it reduce.reduce And map equally , It is also one of the most important methods in functional programming ...map The function of is to change one object into another , and reduce The implementation is to merge all values into one , Please look :
package javase.Lambda; import java.util.Arrays; import java.util.List; public
class Test3 { public static void main(String[] args) { //before java8
List<Double> cost = Arrays.asList(10.0, 20.0,30.0); double sum = 0; for(double
each:cost) { each += each * 0.05; sum += each; } System.out.println("before
java8,"+sum); //after java8 List<Double> list = Arrays.asList(10.0,20.0,30.0);
double sum2 = list.stream().map(x->x+x*0.05).reduce((sum1,x)->sum1+x).get();
System.out.println("after java8,"+sum2); } }

Believe in using map+reduce+lambda The expression is written more than one higher level.

4,filter operation

filter It is also an operation we often use . When manipulating collections , It is often necessary to filter out some elements from the original collection .
package javase.Lambda; import java.util.Arrays; import java.util.List; import
java.util.stream.Collectors; public class Test3 { public static void
main(String[] args) { List<Double> cost = Arrays.asList(10.0, 20.0,30.0,40.0);
List<Double> filteredCost = cost.stream().filter(x -> x >
25.0).collect(Collectors.toList()); filteredCost.forEach(x ->
System.out.println(x)); } }

5, And functional interface Predicate coordination

In addition to supporting functional programming styles at the language level ,Java 8 A package has also been added , be called
java.util.function. It contains many classes , Used to support Java Functional programming . One of them is Predicate, use
java.util.function.Predicate
Functional interfaces and lambda expression , Can to API Method add logic , Support more dynamic behavior with less code .Predicate The interface is very suitable for filtering .
package javase.Lambda; import java.lang.reflect.Array; import
java.util.Arrays; import java.util.List; import java.util.function.Predicate;
public class Test4 { public static void filterTest(List<String> languages,
Predicate<String> condition) { languages.stream().filter(x ->
condition.test(x)).forEach(x -> System.out.println(x + " ")); } public static
void main(String[] args) { List<String> languages =
Arrays.asList("Java","Python","scala","Shell","R");
filterTest(languages,x->x.startsWith("J"));//Java filterTest(languages,x ->
x.endsWith("a"));//Java,scala filterTest(languages,x ->
true);//Java,Python,scala,Shell,R filterTest(languages,x -> false);//
filterTest(languages,x -> x.length() > 4);//Python,scala,Shell, } }

Technology
©2019-2020 Toolsou All rights reserved,
java Comparing attribute values between two objects utilize Python handle Excel data ——xlrd,xlwt library Bidirectional linked list Why? Python Not a future oriented programming language ?Python【 Assignment statement 】 Special lecture , You can't just a=b ah ! Suggest mastering ! utilize Python handle Excel data ——pandas library see SQL-SERVER Data volume and occupied space of database and each table PID The algorithm finally figured out the principle , It was so simple web Two front-end practical games ( Attached source code ) Beginners learn Python Be sure to know what his basic algorithms are ? What is the function ?