当前位置:网站首页>Functional interfaces and method references
Functional interfaces and method references
2022-07-02 11:14:00 【Cold Snowflakes】
Lambda The expression describes , What the abstract method in the interface should do .
actual Lambda The essence is , An object of a class that implements that interface .
The composition of the interface
Constant : The default is public static final
Method : The default is public abstract
stay JAVA8 in , Added default method (public default), Static methods (public static)
stay JAVA9 in , Added private method
For Instance
public interface eatable {
// Abstract method Implementation class Must be implemented
void funAbstract();
// The default method and Static methods Both require method bodies
/** * The default method : Do not force implementation classes to override , Implementation classes can be used directly * Mainly used for interface upgrade , Without breaking existing code */
default void funDefault(){
System.out.println(" The default method ");
}
/** * Static methods in interfaces Can only be called by the interface */
static void funStatic(){
System.out.println(" Static methods ");
}
}
public static void main(String[] args) {
// Realization Abstract method And call The default method
((eatable) () -> System.out.println(" Implement abstract methods ")).funDefault();
// Realization Abstract method And call Abstract method
((eatable) () -> System.out.println(" Implement abstract methods ")).funAbstract();
// Static methods in interfaces Can only be Interface call , Cannot be called by an implementation class
eatable.funStatic(); // OK
((eatable) () -> System.out.println(" Implement abstract methods ")).funStatic(); // Error
}
Method reference ( Use the existing method logic to deal with the abstract method in the interface )
quote Class Static methods
// Parameters of abstract methods Pass all to Referenced static methods
public static void main(String[] args) {
((eatable) s -> Integer.parseInt(s)) // lambda form
.toInt("2349645");
((eatable) Integer::parseInt) // Class name :: Static methods
.toInt("23");
}
interface eatable {
void toInt(String s);
}
quote Class Non static methods
// Parameters of abstract methods Pass all to Referenced non static methods
public static void main(String[] args) {
((eatable)s -> System.out.println(s.toUpperCase()))
.toUpper("fdf");
((eatable)new linshi()::printString)
.toUpper("fsdf"); // Help object , Reference non static methods in classes
}
class linshi {
public void printString(String s){
System.out.println(s.toUpperCase());
}
}
interface eatable {
void toUpper(String s);
}
You can do that :
But pay attention to : The abstract method in the interface The parameter type of the first parameter It has to be linshi, The following parameters are passed to printString Method .
public static void main(String[] args) {
((eatable)(s,a) -> System.out.println(a.toUpperCase()))
.toUpper(new linshi(),"fgwerg");
/** * Use this Class name :: Non static methods When it comes to form * * Be careful The abstract method in the interface The parameter type of the first parameter It has to be linshi * Parameter after All to printString Method */
((eatable)linshi::printString)
.toUpper(new linshi(),"grg");
}
class linshi {
public void printString(String s){
System.out.println(s.toUpperCase());
}
}
interface eatable {
// The first parameter As a caller
void toUpper(linshi a,String s); // The second parameter Give to the printString Method as a parameter
}
Functional interface
Interface with and only one abstract method , A functional interface is lambda The premise of expression .
have access to @FunctionalInterface marked Functional interface .
Using functional interfaces As a parameter , You can pass on the past lambda expression .
public class lambdademo {
public static void main(String[] args) {
ArrayList<String> array = new ArrayList<>();
array.add("ccc");
array.add("aa");
array.add("b");
array.add("dddd");
System.out.println(" Before ordering : " + array);
// Collections.sort(array); // Natural ordering
Collections.sort(array,getComparator()); // Comparator sort
System.out.println(" After ordering : " + array);
}
private static Comparator<String> getComparator(){
// Anonymous inner class mode
// return new Comparator<String>() {
// @Override
// public int compare(String s1, String s2) {
// return s1.length() - s2.length();
// }
// };
// lambda The way , Because the return value is Functional interface
return (s1,s2) -> s1.length() - s2.length();
}
}
Common functional interface
Supplier Interface
public static void main(String[] args) {
// Pass a lambda , It's actually Definition Abstract method Supplier.get The logic of
String string = getString(() -> " Brigitte Lin ");
System.out.println(string);
}
// Set interface generics here by String, Express get Method The return type is String
private static String getString(Supplier<String> sup){
return sup.get();
}
Consumer Interface
public static void main(String[] args) {
// The first parameter is The data passed
// The second parameter is Definition Abstract method accept The logic of
getString(" Xy: ",System.out::print);
}
// Generic String It specifies accept Parameter type
private static void getString(String s, Consumer<String> cn){
// cn.accept(s);
Consumer<String> t = a -> System.out.print(a.length() + 1);
cn.andThen(t).accept(s);
// cn Do it first accept(s)
// t Execute it again accept(s)
}
Predicate Interface
It is often used to judge whether parameters meet specified conditions
boolean test(T t) // Judge the given parameters , The logic of judgment consists of lambda Provide
default Predicate<T> negate()
default Predicate<T> and(Predicate other)
default Predicate<T> or(Predicate other)
public static void main(String[] args) {
boolean res = checkString("fewef", s -> s.length() > 8);
System.out.print(res);
}
private static boolean checkString(String s, Predicate<String> t){
// return t.test(s);
// return t.negate().test(s); // Not
// return t.and(a -> a.startsWith("fy")).test(s); // And
return t.or(a -> a.startsWith("fy")).test(s); // or
}
边栏推荐
- How to implement tabbar title bar with list component
- js中给数组添加元素的方法有哪些
- [AI application] Hikvision ivms-4200 software installation
- 高德根据轨迹画线
- Matlab processing of distance measurement of experimental electron microscope
- Special topic of binary tree -- acwing 3384 Binary tree traversal (known preorder traversal, while building a tree, while outputting middle order traversal)
- Special topic of binary tree -- acwing 47 Path with a certain value in binary tree (preorder traversal)
- C# 文件与文件夹操作
- Primary key policy problem
- 华为应用市场应用统计数据问题大揭秘
猜你喜欢
![[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched](/img/5c/b0030fd5fbc07eb94013f2699c2a04.png)
[quick application] there are many words in the text component. How to solve the problem that the div style next to it will be stretched

2022 love analysis · panoramic report of digital manufacturers of state-owned enterprises
![Binary tree topic -- Luogu p3884 [jloi2009] binary tree problem (DFS for binary tree depth BFS for binary tree width Dijkstra for shortest path)](/img/c2/bb85b681af0f78b380b1d179c7ea49.png)
Binary tree topic -- Luogu p3884 [jloi2009] binary tree problem (DFS for binary tree depth BFS for binary tree width Dijkstra for shortest path)

V2X-Sim数据集(上海交大&纽约大学)

tidb-dm报警DM_sync_process_exists_with_error排查

QT学习日记8——资源文件添加
![[play with FPGA learning 2 in simple terms ----- design skills (basic grammar)]](/img/50/22f2fa8fd606572b13a18cc889ca2e.png)
[play with FPGA learning 2 in simple terms ----- design skills (basic grammar)]

enumrate的start属性的坑

Special topic of binary tree -- acwing 1497 Traversal of the tree (use post and mid order traversal to build a binary tree)

Nodejs+express+mysql simple blog building
随机推荐
One trick to quickly realize custom application titlebar
TIPC Service and Topology Tracking4
如何用list组件实现tabbar标题栏
QT learning diary 7 - qmainwindow
【深入浅出玩转FPGA学习2----设计技巧(基本语法)】
二叉树专题--【深基16.例7】普通二叉树(简化版)(multiset 求前驱 后继 哨兵法)
Pit of the start attribute of enumrate
Jenkins安装
[applinking practical case] share in app pictures through applinking
快应用中实现自定义抽屉组件
Filtering of PCL
PCL eigen introduction and simple use
JVM garbage collector
JSP webshell free -- the basis of JSP
Nodejs+express+mysql simple blog building
PCL extracts a subset from a point cloud
sqlite 修改列类型
TIPC protocol
如何使用IDE自动签名调试鸿蒙应用
Binary tree topic -- p1030 [noip2001 popularization group] find the first order