The functional interface of Java

Xiangxi assassin Wang Hu 2021-02-23 16:49:31
functional interface java


Functional programming

Functional programming ( English : functional programming) Or called Function programming Functional programming , It's a kind of Programming paradigm , It will Computer computing As function operation , And avoid using Program status as well as Variable objects .
Compared with Command programming , Functional programming emphasizes the result of program execution more than the process of execution , It advocates the use of a few simple execution units to make the results progressive , Complex operations are derived layer by layer , Rather than designing a complex execution process .
Pure functional programming languages are usually not allowed to be used directly Program status as well as Variable objects .

Functional programming does not need to consider " Deadlock "(deadlock), Because it doesn't modify variables , So there's no such thing as " lock " Thread problem . You don't have to worry about a thread's data , Modified by another thread , So it's safe to spread the work across multiple threads , Deploy " Concurrent programming "

OO(object oriented, object-oriented ) It's abstract data ,FP(functional programming, Functional programming ) It's abstract behavior .

Lambda expression

  1. Lambda Expressions are function definitions written in the least possible syntax :
  2. Lambda Expressions produce functions , Rather than class . stay JVM(Java Virtual Machine,Java virtual machine ) On , Everything is a class , So performing various operations behind the scenes makes Lambda It looks like a function —— But as a programmer , You can happily pretend that they “ It's just a function ”.
  3. Lambda Grammar as little as possible , This is just to make Lambda Easy to write and use .

Functional interface

Method references and Lambda The expression must be assigned , At the same time, the compiler needs to recognize the type information to ensure that the type is correct . Lambda In particular, expressions introduce new requirements . Code example :

x -> x.toString()

We know that the return type here must be String, but x What kind is it ?

Lambda Expressions contain type derivation ( The compiler automatically deduces type information , Avoid programmers explicitly declaring ). The compiler must be able to deduce in some way x The type of .

Here's number one 2 A code example :

(x, y) -> x + y

Now? x and y It can be any support + The data type of the operator connection , It can be two different numeric types or 1 individual String Add any one can be automatically converted to String Data type of ( This includes most types ). however , When Lambda When an expression is assigned a value , The compiler has to make sure that x and y To generate the correct code .

This problem also applies to method references . Suppose you want to deliver System.out :: println To the method you're writing , How do you know the type of parameter passed to the method ?

To solve this problem ,Java 8 Introduced java.util.function package . It contains a set of interfaces , These interfaces are Lambda Target types for expressions and method references . Each interface contains only one abstract method , It's called the functional method .

When writing interfaces , have access to @FunctionalInterface Annotations enforce this “ Functional method ” Pattern . One Functional interface Even if you don't add @FunctionalInterface annotation , with lambda In combination with , But such a functional interface is It's easy to make mistakes Of : If someone adds another method to the interface definition , At this time , This interface is no longer functional , And the compilation process will fail . In order to overcome this problem of functional interface Vulnerability And be able to Make a clear statement The intention of interface as a functional interface , It is recommended to use this annotation explicitly .

java.util.function Packages are designed to create a complete set of target interfaces , In general, we don't need to define our own interface . This is mainly because basic types produce a small number of interfaces . If you know the naming pattern , As the name suggests, you know what a particular interface does .

Here are the basic naming principles :

  1. If you only deal with objects instead of basic types , The name is ‘Supplier’,Consumer,Predicate,‘Operator’,Function etc. . Parameter types are added through generics .
  2. If the received parameter is a basic type , It is indicated by the first part of the name , Such as LongConsumer,DoubleFunction,IntPredicate etc. , But basically Supplier Type exception .
  3. If the return value is of the base type , Then use To Express , Such as ToLongFunction <T> and IntToLongFunction.
  4. If the return value type is the same as the parameter type , Is an operator : A single parameter uses UnaryOperator, Two parameters use BinaryOperator.
  5. If two parameters are received and the return value is Boolean , Is a predicate (Predicate).
  6. If the two parameters received are of different types , Then there is one in the name Bi.

The following table describes java.util.function Target types in ( Including exceptions ):

features Functional method name Example
No parameter ;
No return value
Runnable
(java.lang)
run()
Runnable
No parameter ;
Any return type
Supplier
get()
getAs type ()
Supplier<T>
BooleanSupplier
IntSupplier
LongSupplier
DoubleSupplier
No parameter ;
Any return type
Callable
(java.util.concurrent)
call()
Callable<V>
1 Parameters ;
No return value
Consumer
accept()
Consumer<T>
IntConsumer
LongConsumer
DoubleConsumer
2 Parameters Consumer BiConsumer
accept()
BiConsumer<T,U>
2 Parameters Consumer;
1 quote ;
1 Basic types
Obj type Consumer
accept()
ObjIntConsumer<T>
ObjLongConsumer<T>
ObjDoubleConsumer<T>
1 Parameters ;
Different return types
Function
apply()
To type and type To type
applyAs type ()
Function<T,R>
IntFunction<R>
LongFunction<R>
DoubleFunction<R>
ToIntFunction<T>
ToLongFunction<T>
ToDoubleFunction<T>
IntToLongFunction
IntToDoubleFunction
LongToIntFunction
LongToDoubleFunction
DoubleToIntFunction
DoubleToLongFunction
1 Parameters ;
The return type is the same
UnaryOperator
apply()
UnaryOperator<T>
IntUnaryOperator
LongUnaryOperator
DoubleUnaryOperator
2 Same parameter type ;
The return type is the same
BinaryOperator
apply()
BinaryOperator<T>
IntBinaryOperator
LongBinaryOperator
DoubleBinaryOperator
2 Same parameter type ;
Return integer
Comparator
(java.util)
compare()
Comparator<T>
2 Parameters ;
Return to Boolean
Predicate
test()
Predicate<T>
BiPredicate<T,U>
IntPredicate
LongPredicate
DoublePredicate
Basic types of parameters ;
Returns the basic type
type To type Function
applyAs type ()
IntToLongFunction
IntToDoubleFunction
LongToIntFunction
LongToDoubleFunction
DoubleToIntFunction
DoubleToLongFunction
2 Different parameter types Bi operation
( Different method names )
BiFunction<T,U,R>
BiConsumer<T,U>
BiPredicate<T,U>
ToIntBiFunction<T,U>
ToLongBiFunction<T,U>
ToDoubleBiFunction<T>

This table only provides some conventional solutions . Through the above table , You should be more or less able to derive more lines of functional interfaces on your own .

According to this naming convention , Here are some examples of declarations :


Runnable runnable = () -> {};
Callable<Integer> callable = () -> (new Random().nextInt());
Supplier<Integer> supplier = () -> (new Random().nextInt());
IntSupplier intSupplier = () -> (new Random().nextInt());
Consumer<String> consumer = s -> System.out.print(s);
Consumer<String> consumer1 = System.out::println;
BiConsumer<Integer,Long> biConsumer = (i,l) -> System.out.print(i+l);
ObjIntConsumer<Result> objIntConsumer = (r,i) -> System.out.print(r.getMessage() + i);
//Operator Only basic types are supported
UnaryOperator<Integer> unaryOperator = i -> i++;
BinaryOperator<Integer> binaryOperator = (i1,i2) -> i1+i2;
// Because it's usually used to compare reference types , So there's no way to name basic types
// If not for comparative purposes , have access to Function
Comparator<Result> comparator = (r1,r2) -> r1.getCode() - r2.getCode(); //Comparator.comparingInt(Result::getCode)
Predicate<Integer> predicate = i -> i > 0;
IntPredicate intPredicate = i -> i > 0;
BiPredicate<Integer,Result> biPredicate = (i,r) -> i > r.getCode();
Function<String,Integer> function = s -> Integer.parseInt(s); //Integer::parseInt
ToIntFunction<String> toIntFunction = Integer::parseInt;
IntFunction<String> intFunction = Integer::toString;
BiFunction<Integer,Long,String> biFunction = (i,l) -> "" + i + l;
版权声明
本文为[Xiangxi assassin Wang Hu]所创,转载请带上原文链接,感谢
https://javamana.com/2021/02/20210223164742974y.html

  1. k8s-prometheus
  2. Linux Disk Command
  3. Linux FS
  4. 使用docker-compose &WordPress建站
  5. Linux Command
  6. This time, thoroughly grasp the depth of JavaScript copy
  7. Linux Disk Command
  8. Linux FS
  9. Using docker compose & WordPress to build a website
  10. Linux Command
  11. 摊牌了,我 HTTP 功底贼好!
  12. shiro 报 Submitted credentials for token
  13. It's a showdown. I'm good at it!
  14. Shiro submitted credentials for token
  15. Linux Stress test
  16. Linux Root Disk Extension
  17. Linux Stress test
  18. Linux Root Disk Extension
  19. Redis高级客户端Lettuce详解
  20. springboot学习-综合运用(一)
  21. 忘记云服务器上MySQL数据库的root密码时如何重置密码?
  22. Detailed explanation of lettuce, an advanced client of redis
  23. Springboot learning integrated application (1)
  24. Linux File Recover
  25. Linux-Security
  26. How to reset the password when you forget the root password of MySQL database on the cloud server?
  27. Linux File Recover
  28. Linux-Security
  29. LiteOS:盘点那些重要的数据结构
  30. Linux Memory
  31. Liteos: inventory those important data structures
  32. Linux Memory
  33. 手把手教你使用IDEA2020创建SpringBoot项目
  34. Hand in hand to teach you how to create a springboot project with idea2020
  35. spring boot 整合swagger2生成API文档
  36. Spring boot integrates swagger2 to generate API documents
  37. linux操作系统重启后 解决nginx的pid消失问题
  38. Solve the problem of nginx PID disappearing after Linux operating system restart
  39. JAVA版本号含义
  40. The meaning of java version number
  41. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(二)
  42. 开源办公开发平台丨Mysql5.7两套四节点主从结构环境搭建教程(一)
  43. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (2)
  44. HTTP的“无状态”和REST的“状态转换”
  45. Open source office development platform mysql5.7 two sets of four node master-slave structure environment building tutorial (1)
  46. 【大数据哔哔集20210128】使用Hive计算环比和同比
  47. 【大数据哔哔集20210125】Kafka将逐步弃用对zookeeper的依赖
  48. 【大数据哔哔集20210124】有人问我Kafka Leader选举?我真没慌
  49. 【大数据哔哔集20210123】别问,问就是Kafka高可靠
  50. Spring 事务、异步和循环依赖有什么关系?
  51. Spring 动态代理时是如何解决循环依赖的?为什么要使用三级缓存?
  52. "Stateless" of HTTP and "state transition" of rest
  53. [big data bibiji 20210128] use hive to calculate month on month and year on year
  54. [big data bibiji 20210125] Kafka will gradually abandon its dependence on zookeeper
  55. [big data beeps 20210124] someone asked me about Kafka leader election? I'm not in a panic
  56. [big data bibiji 20210123] don't ask, ask is Kafka highly reliable
  57. jQuery Gantt Package 在Visual Studio中创建一个新的ASP.NET项目
  58. What is the relationship between spring transactions, asynchrony, and circular dependencies?
  59. How to solve circular dependency in spring dynamic proxy? Why use level 3 caching?
  60. Unicode码的二进制转换(Java)