当前位置:网站首页>Lamaba expression learning and common functional interfaces
Lamaba expression learning and common functional interfaces
2022-06-28 04:14:00 【smartjiang-java】
List of articles
Lambda expression
One 、Lambda Expression Introduction
What is? Lambda?
Lambda yes JAVA 8 New features added , To put it bluntly ,Lambda Is an anonymous function
Why use Lambda
Use Lambda Expression can be a very concise implementation of an interface method
Lambda Requirements for interface
Although it can be used Lambda Expression to simply implement some interfaces , But not all interfaces can be used Lambda Expression to implement , Require the defined in the interface
1: The abstract method that must be implemented can only be one
2: stay JAVA8 in , Added a new feature to the interface :default
have access to default Modify the interface method , The modified method can be implemented by default in the interface
@FunctionalInterface
@FunctionalInterface
Modifying the , There is only one abstract method in the interface
Two 、Lambda Basic grammar of
1. grammar
/** * (): Used to describe parameter list * {}: Used to describe method body Sometimes you can omit * ->: Lambda Operator pronounce as goes to * example Test t=()->{System.out.println("hello word")}; Braces can be omitted */
2. Create multiple interfaces
// No parameter, no return value interface
@FunctionalInterface
public interface LambdaNoneReturnNoneParmeter {
void test();
}
// No return value has a single parameter
@FunctionalInterface
public interface LambdaNoneReturnSingleParmeter {
void test(int n);
}
// No return value Interface with multiple parameters
@FunctionalInterface
public interface LambdaNoneReturnMutipleParmeter {
void test(int a,int b);
}
// There is a return value No parameter interface
@FunctionalInterface
public interface LambdaSingleReturnNoneParmeter {
int test();
}
// There is a return value An interface with a single parameter
@FunctionalInterface
public interface LambdaSingleReturnSingleParmeter {
int test(int n);
}
// There is a return value Interface with multiple parameters
@FunctionalInterface
public interface LambdaSingleReturnMutipleParmeter {
int test(int a,int b);
}
3. Create test class
package com.alan.learn.syntax;
import com.alan.learn.interfaces.*;
public class Syntax1 {
public static void main(String[] args) {
// 1.Lambda The basic syntax for expressions
// Lambda Is an anonymous function The general focus is on the following two key points
// parameter list Method body
/** * (): Used to describe parameter list * {}: Used to describe method body * ->: Lambda Operator pronounce as goes to */
// No parameter no return
LambdaNoneReturnNoneParmeter lambda1=()->{
System.out.println("hello word");
};
lambda1.test();
// No return value Single parameter
LambdaNoneReturnSingleParmeter lambda2=(int n)->{
System.out.println(" Parameter is :"+n);
};
lambda2.test(10);
// No return value Multiple parameters
LambdaNoneReturnMutipleParmeter lambda3=(int a,int b)->{
System.out.println(" Parameters and yes :"+(a+b));
};
lambda3.test(10,12);
// There is a return value No parameter
LambdaSingleReturnNoneParmeter lambda4=()->{
System.out.println("lambda4:");
return 100;
};
int ret=lambda4.test();
System.out.println(" The return value is :"+ret);
// There is a return value Single parameter
LambdaSingleReturnSingleParmeter lambda5=(int a)->{
return a*2;
};
int ret2= lambda5.test(3);
System.out.println(" Single parameter ,lambda5 The return value is :"+ret2);
// There is a return value Multiple parameters
LambdaSingleReturnMutipleParmeter lambda6=(int a,int b)->{
return a+b;
};
int ret3=lambda6.test(12,14);
System.out.println(" Multiple parameters ,lambda6 The return value is :"+ret3);
}
}
3、 ... and 、 The grammar is simple
1. Parameter type
/** * The grammar is simple * **1. Parameter type : Or don't write , Or write it all ** * Because in the abstract method of the interface , The quantity type of the parameter has been defined So in Lambda The type of parameter in the expression can be omitted * remarks : Omit the type if necessary , Then the type of each parameter should be omitted , Never omit one without omitting the other LambdaNoneReturnMutipleParmeter lambda1=(int a,int b)-> { System.out.println("hello world"); }; It can be reduced to : LambdaNoneReturnMutipleParmeter lambda1=(a,b)-> { System.out.println("hello world"); }; 2. Parameter parentheses
/** * 2. Parameter parentheses * If in the parameter list ,** The number of parameters is only one In this case, the parentheses can be omitted ** LambdaNoneReturnSingleParmeter lambda2=(a)->{ System.out.println("hello world"); }; It can be reduced to : LambdaNoneReturnSingleParmeter lambda2= a->{ System.out.println("hello world"); }; 3. Method braces
/** * 3. Method braces * ** If there is only one statement in the method body , In this case, braces can be omitted ** LambdaNoneReturnSingleParmeter lambda3=a->{ System.out.println("hello world"); }; It can be reduced to : LambdaNoneReturnSingleParmeter lambda3=a->System.out.println("hello world"); 4. Curly braces complement
/** * 4.** If the only statement in the method body is a return statement * When the thief omits the braces You must also omit return** LambdaSingleReturnNoneParmeter lambda4=()->{ return 10; }; It can be reduced to : LambdaSingleReturnNoneParmeter lambda4=()->10; 5. multi-parameter , There is a return value Streamlining
/** LambdaSingleReturnNoneParmeter lambda4=(a,b)->{ return a+b; }; It can be reduced to : LambdaSingleReturnMutipleParmeter lambda5=(a,b)->a+b; Four 、Lambda Advanced grammar
1. Method reference ( General method and static method )
In practical application , An interface will call the same implementation in many places , for example :
/** LambdaSingleReturnMutipleParmeter lambda1=(a,b)->a+b; LambdaSingleReturnMutipleParmeter lambda2=(a,b)->a+b; In this way, the specific implementation method should be written every time a+b, If the requirements change , Then every implementation needs to be changed , Based on this situation , Subsequent implementations can be changed to defined Method , Just call it when you need it
grammar :
/** * Method reference : * Can quickly put a Lambda The implementation of the expression points to an implemented method * The subordinate of the method If it's a static method It belongs to a class Other words are subordinate objects * grammar : The subordinate of the method :: Method name * Be careful : * 1. In the referenced method , The number and type of parameters must be consistent with the methods defined in the interface * 2. The type of return value must also be consistent with the method in the interface */
example :
package com.alan.learn.syntax;
import com.alan.learn.interfaces.LambdaSingleReturnSingleParmeter;
public class Syntax3 {
public static void main(String[] args) {
LambdaSingleReturnSingleParmeter lambda1=a->a*2;
LambdaSingleReturnSingleParmeter lambda2=a->a*2;
LambdaSingleReturnSingleParmeter lambda3=a->a*2;
// simplify
LambdaSingleReturnSingleParmeter lambda4=a->change(a);
// Method reference
LambdaSingleReturnSingleParmeter lambda5=Syntax3::change;
}
/** * Custom implementation method */
private static int change(int a){
return a*2;
}
}
2. Method reference ( Construction method ): An object of a class is returned from a method in an interface
At present, there is an entity class
public class Person {
public String name;
public int age;
public Person() {
System.out.println("Person The parameterless construction method of ");
}
public Person(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Person The parameterized construction method of ");
}
}
demand :
Two interfaces , There's a way for each , The method of an interface needs to reference Person The nonparametric structure of , The method of an interface needs to reference Person The parametric structure of Used to return two Person object , example :
interface PersonCreater{
// adopt Person Implementation of parameterless construction of
Person getPerson();
}
interface PersonCreater2{
// adopt Person The parameterized construction of
Person getPerson(String name,int age);
}
Then you can write :
public class Syntax4 {
public static void main(String[] args) {
PersonCreater creater=()->new Person();
// The reference is Person The nonparametric structure of
//PersonCreater The method of the interface points to Person Methods
PersonCreater creater1=Person::new; // Equivalent to the above ()->new Person()
// What's actually called is Person The nonparametric structure of Equivalent to the interface in getPerson() Rewrite as new Person().
Person a=creater1.getPerson();
// The reference is Person The parametric structure of
PersonCreater2 creater2=Person::new;
Person b=creater2.getPerson(" Zhang San ",18);
}
}
Be careful : Whether to refer to a parameterless construct or a parameterless construct Lies in the method parameters defined by the interface
5、 ... and 、 Comprehensive practice
1. Set sort case
package com.alan.exercise;
import com.alan.learn.data.Person;
import java.util.ArrayList;
public class Exercise1 {
public static void main(String[] args) {
// demand : Known in a ArrayList There are several Person object , Will these Person Objects are arranged in descending order by age
ArrayList<Person> list=new ArrayList<>();
list.add(new Person(" Zhang San ",10));
list.add(new Person(" Li Si ",12));
list.add(new Person(" Wang Wu ",13));
list.add(new Person(" Zhao Liu ",14));
list.add(new Person(" Li lei ",11));
list.add(new Person(" Han Meimei ",8));
list.add(new Person("jack",10));
System.out.println(" Before ordering :"+list);
// Pass the basis of arrangement into The specific method points to The internal elements of age Subtracting the sort It will be arranged in descending order according to the positive and negative of the results
//list.sort Need to use Comparator The comparer sorts this list to compare elements
// and Comparator yes @FunctionalInterface Modified interface , Must realize the inside int compare(T o1, T o2) Method
// int compare(T o1, T o2); positive sequence :o1-o2 In reverse order :o2-o1
// Allied ,Collectios.sort(),Arrays.sort() All that came in was Comparator Interface
list.sort((o1, o2) -> o2.age-o1.age);
System.out.println(" After ordering :"+list);
}
}
2.Treeset Sort cases
package com.alan.exercise;
import com.alan.learn.data.Person;
import java.util.TreeSet;
public class Exercise2 {
public static void main(String[] args) {
/**Treeset Order by yourself * Print directly , I will report an error, but now I don't know Person Who is big and who is small cannot be sorted * resolvent : * Method 1:Person Class implementation Comparable<Person> * public class Person implements Comparable<Person> { * @Override * public int compareTo(Person o) { * return o.age>=this.age?1:-1; * } * Method 2: stay TreeSet The constructor passed in Comparator Interface , Provide a comparison rule by yourself , Instantiation TreeSet*/
// Be careful : stay TreeSet If Comparator The return value is 0, I will judge that these two elements are de duplication , One less will be printed Person object
// TreeSet<Person> set=new TreeSet<>((o1, o2) -> o2.age-o1.age);
// At this point, we will modify the method
TreeSet<Person> set=new TreeSet<>((o1, o2) ->{
if(o1.age>=o2.age){
return -1;
}else {
return 1;
}
});
set.add(new Person(" Zhang San ",10));
set.add(new Person(" Li Si ",12));
set.add(new Person(" Wang Wu ",13));
set.add(new Person(" Zhao Liu ",14));
set.add(new Person(" Li lei ",11));
set.add(new Person(" Han Meimei ",8));
set.add(new Person("jack",10));
System.out.println(set);
}
}
3. Traversal of the set
package com.alan.exercise;
import java.util.ArrayList;
import java.util.Collections;
public class Exercise3 {
public static void main(String[] args) {
ArrayList<Integer> list=new ArrayList<>();
Collections.addAll(list,1,2,3,4,5,6,7,8,9);
/** * list.forEach(Consumer<? super E> action) * api A document explaining : Yes Each element in the collection performs the given operation , Until all elements are handled or an action throws an exception . * Bring every element in the collection into the interface Consumer Methods accept in Then the method accept References to us * Output all elements in the collection * list.forEach(System.out::println); */
// All even numbers in the output set
list.forEach(ele->{
if(ele%2==0){
System.out.println(ele);
}
});
}
}
4. Delete the qualified elements in the collection
package com.alan.exercise;
import com.alan.learn.data.Person;
import java.util.ArrayList;
public class Exercise4 {
public static void main(String[] args) {
ArrayList<Person> list=new ArrayList<>();
list.add(new Person(" Zhang San ",10));
list.add(new Person(" Li Si ",12));
list.add(new Person(" Wang Wu ",13));
list.add(new Person(" Zhao Liu ",14));
list.add(new Person(" Li lei ",11));
list.add(new Person(" Han Meimei ",8));
list.add(new Person("jack",10));
// Delete a collection older than 12 The elements of
/** * Previous iterators * ListIterator<Person> it = list.listIterator(); * while (it.hasNext()){ * Person ele=it.next(); * if(ele.age>12){ * it.remove(); * } * } */
/** * lambda Realization * Logic * Bring every element in the collection into the interface Predicate Of test In the method , * If the return value is true, Then delete this element */
list.removeIf(ele->ele.age>10);
System.out.println(list);
}
}
5. Open up a thread Make a digital output
package com.alan.exercise;
public class Exercise5 {
public static void main(String[] args) {
/** * adopt Runnable To instantiate threads */
Thread t=new Thread(()->{
for(int i=0;i<100;i++){
System.out.println(i);
}
});
t.start();
}
}
6、 ... and 、 System built-in functional interface
package com.alan.functional;
import java.util.function.*;
public class FunctionalInterface {
public static void main(String[] args) {
// Predicate<T> : Parameter is T Return value boolean, Determine whether the input object meets a certain condition for example list.removeif()
// Later, if an interface needs to specify a parameter of type , return boolean Can point to Predicate
// IntPredicate int -> boolean
// LongPredicate long -> boolean
// DoublePredicate double -> boolean
// Consumer<T> : Parameter is T No return value (void), Perform a consumption operation on a given parameter for example list.foreach()
// IntConsumer int ->void
// LongConsumer long ->void
// DoubleConsumer double ->void
// Function<T,R> : Parameter type T Return value R, Get another type of data from one type of data
// IntFunction<R> int -> R
// LongFunction<R> long -> R
// DoubleFunction<R> double -> R
// IntToLongFunction int -> long
// IntToDoubleFunction int -> double
// LongToIntFunction long -> int
// LongToDoubleFunction long -> double
// DoubleToLongFunction double -> long
// DoubleToIntFunction double -> int
// Supplier<T> : Parameters nothing Return value T , Used to get the object data of the type specified by a generic parameter
// UnaryOperator<T> : Parameters T Return value T Inherit Function<T,R> Interface
// BiFunction<T,U,R> : Parameters T、U Return value R
// BinaryOperator<T> : Parameters T、T Return value T Inherit BiFunction<T,U,R> Interface
// BiPredicate<T,U> : Parameters T、U Return value boolean
// BiConsumer<T,U> : Parameters T、U No return value
/** * frequently-used Functional interface * Predicate<T>、Consumer<T>、Function<T,R>、Supplier<T> */
}
}
7、 ... and 、Lambda Closure
### example 1
package com.alan.closure;
import java.util.function.Supplier;
public class ClosureDemo {
public static void main(String[] args) {
/** * lambda The closure of will elevate the life cycle of the enclosing variable * So local variables num stay getNumber() The method is get() quote Not in getNumber() Destroy after method execution * This method can obtain the local variables of a method externally */
int n=getNumber().get();
System.out.println(n);
}
private static Supplier<Integer> getNumber(){
int num=10;
/** * Supplier supplier=()->num; * return supplier; */
return ()->{
return num;
};
}
}
example 2
package com.alan.closure;
import java.util.function.Consumer;
public class ClosureDemo2 {
public static void main(String[] args) {
int a=10;
Consumer<Integer> c=ele->{
System.out.println(a+1);
//System.out.println(ele);
//System.out.println(a++); Will report a mistake
// stay lambda Reference local variables in This variable must be a constant
};
//a++; This will also lead to internal error reporting
// If a local variable has been referenced internally After the parameter is passed It's still printed 10
c.accept(1);
}
}
Be careful : This article only represents the personal views of novice bloggers , If something is wrong or there is a better idea through the technology , Welcome to leave a message , Sharing and communication make us progress , thank you .
边栏推荐
- Iso8191 test is mentioned in as 3744.1. Are the two tests the same?
- Market competitiveness of robot programming education
- leetcode:714. 买卖股票的最佳时机含手续费【dp双状态】
- MSc 307 (88) (2010 FTPC code) Part 5 low flame spread test
- Supplementary questions of monthly competition
- 《性能之巅第2版》阅读笔记(二)--性能观察工具
- Meichuang data security management platform has obtained the evaluation certificate of "data security product capability verification plan" of the Institute
- Staggered and permutation combination formula
- 05 mongodb summary of various column operations
- Reading notes of top performance version 2 (II) -- CPU monitoring
猜你喜欢

Pychart shares third-party modules among different projects

Door level modeling - learning notes

Open the field of maker education and creation

leetcode:714. 买卖股票的最佳时机含手续费【dp双状态】

10:00面试,10:02就出来了 ,问的实在是太...

Introduction notes to machine learning

leetcode - 329. 矩阵中的最长递增路径

多项目开发入门,基础设计 类库项目使用

美创入选“2022 CCIA中国网络安全竞争力50强”榜单

Introduction to multi project development, basic design class library project use
随机推荐
Introduction notes to machine learning
Go语言学习教程(十四)
单一职责原则
品达通用权限系统(Day 5~Day 6)
Unity C # e-learning (11) -- custom protocol generation tool
01 overview, application scenarios, Download methods, connection methods and development history of mongodb
Sorting from one stack to another
How to apply for ASTM E108 flame retardant test for photovoltaic panels?
leetcode:494. All methods of adding and subtracting operators to the array to get the specified value
有关函数模板的那些小知识-.-
@Several scenarios of transactional failure
27年,微软IE结束了!
Pointer linked list
多项目开发入门,基础设计 类库项目使用
Meichuang data security management platform has obtained the evaluation certificate of "data security product capability verification plan" of the Institute
Moonbeam集成Coin98,给予用户在多链道路上的更多选择
Introversion, lying flat and midlife crisis
Backtracking maze problem
MSC 307(88) (2010 FTPC Code)第2部分烟气和毒性测试
MSc 307 (88) (2010 FTPC code) Part 5 low flame spread test