当前位置:网站首页>Step by step towards responsive programming (III) - common functional interfaces - function < T, R>
Step by step towards responsive programming (III) - common functional interfaces - function < T, R>
2022-07-20 19:58:00 【Pujiang ape】
The functional interface was introduced earlier Predicate and Consumer, This article continues with another functional interface Function<T, R>, This interface is also located in java.util.function In bag , Its role can be seen as the combination of consumers and producers , That is to consume certain raw materials and then produce certain products , Continue to analyze the source code first .
The source code parsing
package java.util.function;
import java.util.Objects;
/** * Represents a function that accepts one argument and produces a result. * The method in this interface receives a parameter and outputs a result * * <p>This is a <a href="package-summary.html">functional interface</a> * whose functional method is {@link #apply(Object)}. * * @param <T> the type of the input to the function * @param <R> the type of the result of the function * * @since 1.8 */
@FunctionalInterface
public interface Function<T, R> {
/** * Applies this function to the given argument. * This method processes the input parameters , And get a result * @param t the function argument * @return the function result */
R apply(T t);
/** * Returns a composed function that first applies the {@code before} * function to its input, and then applies this function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * This method combines two function Are combined , Get a new one function, If there is one in the process of combination function Something is wrong , Exceptions are handled by the caller . Combinatorial logic is , Put one of them function Pass in as a parameter (before), stay compose Internal access before Result , And pass it on to the second function Make a new function And back to * @param <V> the type of input to the {@code before} function, and to the * composed function * @param before the function to apply before this function is applied * This sentence is so difficult to understand , Simply put, it is to put a function As a parameter * @return a composed function that first applies the {@code before} * function and then applies this function * take before function The result of is passed to the current function, And back to . * @throws NullPointerException if before is null * * @see #andThen(Function) */
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/** * Returns a composed function that first applies this function to * its input, and then applies the {@code after} function to the result. * If evaluation of either function throws an exception, it is relayed to * the caller of the composed function. * This function and compose The function is a little bit like , But in a different order . This function executes the caller first , Re execution andThen Parameters of , Pass the result of the caller to function Use , And return a function. * @param <V> the type of output of the {@code after} function, and of the * composed function * @param after the function to apply after this function is applied * @return a composed function that first applies this function and then * applies the {@code after} function * @throws NullPointerException if after is null * * @see #compose(Function) */
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/** * Returns a function that always returns its input argument. * take apply The parameters of are returned in front of the result * @param <T> the type of the input and output objects to the function * @return a function that always returns its input argument */
static <T> Function<T, T> identity() {
return t -> t;
}
}
case analysis
By dealing with User Cases to analyze the use of each method . Two classes are provided User and UserEntity:
User
public class User {
private int age;
private String name;
/** * @return the age */
public int getAge() {
return age;
}
/** * @param age * @param name */
public User(int age, String name) {
this.age = age;
this.name = name;
}
/** * @param age the age to set */
public void setAge(int age) {
this.age = age;
}
/** * @return the name */
public String getName() {
return name;
}
/** * @param name the name to set */
public void setName(String name) {
this.name = name;
}
}
UserEntity
public class UserEntity {
private int age;
private String name;
private int type;
/** * @param age * @param name * @param type */
public UserEntity(int age, String name, int type) {
this.age = age;
this.name = name;
this.type = type;
}
/** * @return the age */
public int getAge() {
return age;
}
/** * @param age the age to set */
public void setAge(int age) {
this.age = age;
}
/** * @return the name */
public String getName() {
return name;
}
/** * @param name the name to set */
public void setName(String name) {
this.name = name;
}
/** * @return the type */
public int getType() {
return type;
}
/** * @param type the type to set */
public void setType(int type) {
this.type = type;
}
/* (non-Javadoc) * @see java.lang.Object#toString() */
@Override
public String toString() {
return "UserEntity {age=" + age + ", name=" + name + ", type=" + type + "}";
}
}
apply
A set of User Into a group User Entity, according to User Age to define the user level ( Ordinary users ,vip,svip), The user level is User Entity A field of , So the input parameter is List, The return is List .
Structural data
User user1 = new User(10, " Zhang San ");
User user2 = new User(15, " Li Si ");
User user3 = new User(16, " Wang Wu ");
User user4 = new User(20, " Zhao Liu ");
User user5 = new User(25, " Panax notoginseng ");
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
users.add(user5);
Define transformation logic
/** * Convert users to user entities * age<=15:GENERAL * 15<age<=20:VIP * 20<age:SVIP * @param Function<List<User>,List<UserEntity>> */
static Function<List<User>,List<UserEntity>> multiUsersToEntities(List<User> users){
Function<List<User>,List<UserEntity>> function = t-> {
List<UserEntity> userEntities = new ArrayList<>();
int age;
String name;
UserEntity userEntity;
for(User user:t){
age = user.getAge();
name = user.getName();
if( age<=15){
userEntity = new UserEntity(age, name, Type.GENERAL.getCode());
}else if (age > 15 && age <=20){
userEntity = new UserEntity(age, name, Type.VIP.getCode());
}else{
userEntity = new UserEntity(age, name, Type.SVIP.getCode());
}
userEntities.add(userEntity);
}
return userEntities;
};
return function;
}
Start conversion
Function<List<User>,List<UserEntity>> function = multiUsersToEntities(users);
List<UserEntity> uEntities = function.apply(users);
Conversion result
uEntities.stream().forEach(u->System.out.println(u.toString()));
The result of successful conversion is as follows
UserEntity {
age=10, name= Zhang San , type=3}
UserEntity {
age=15, name= Li Si , type=3}
UserEntity {
age=16, name= Wang Wu , type=1}
UserEntity {
age=20, name= Zhao Liu , type=1}
UserEntity {
age=25, name= Panax notoginseng , type=2}
compose
According to the understanding in the notes, I feel embarrassed , Here is simply to combine the two functions , Execute first compose The inner function executes the outer function , For the sake of understanding, leave the above example .
Define two functions as follows :
// Double the input value
Function<Integer,Integer> function2 = t-> t*2;
// Square the input value
Function<Integer,Integer> function3 = t-> t*t;
System.out.println("compose result :"+function2.compose(function3).apply(3));
The result is :compose result :18
andThen
Same as compose similar , It is also a combination of two functions , But in a different order , Let's do it first andThen The outer function , Re execution andThen Functions inside . Continue to take the above two functions as examples
System.out.println("andThen result :"+function2.andThen(function3).apply(3));
The result is :andThen result :36
identity
identiy I haven't used it , Here's an example , Continue to update after further understanding .
Function<Integer,Integer> function4 = Function.identity();
System.out.println("identity result :"+function4.apply(3));
The result is :identity result :3
summary
The content is very simple , stay java8 Of Stream in ,Function It's widely used , The following blog posts will introduce . Finally, I hope this article can help you , I wish you all in IT Take fewer detours on the road , Green lights all the way, no traffic jam , Pass the test ,bug Second solution !
Source download
边栏推荐
- 大咖说·图书分享 | HaaS 物联网设备云端一体开发框架
- VO、DTO、DO、PO区分和使用
- C language structure
- MySQL基础——数据库索引与事务
- 赛迪发布《湖仓一体技术研究报告》,巨杉数据库入选国内企业典型代表
- 为什么游戏里的都是伪随机,做不出真随机?
- 基于C语言的自动机dot画图脚本设计
- 50个名额限量开放|带着OceanBase年度发布会的消息走来了!
- MultiHead-Attention和Masked-Attention的机制和原理
- Preparation of water-soluble sodium ferulate albumin nanoparticles /p-cs-np loaded teniposide multilayer coated serum protein nanoparticles
猜你喜欢
MySQL common statement knowledge points
【iVX从入门到精通 · 开篇】初始iVX——零代码的可视化编程语言
Promise实现
Preparation of tacrolimus loaded HSA protein nanoparticles / dct-bsa docetaxel albumin nanoparticles / serum albumin hyaluronic acid nanoparticles
海上风电消防火灾报警系统中消防主机超远距离联网方案
Qt QTextEdit 设置 QScrollBar 样式表不生效解决方案
为什么游戏里的都是伪随机,做不出真随机?
DTX GA BSA NPs loaded docetaxel and gambogic acid albumin nanoparticles / thioguanine albumin nanoparticles
【超详细图解】FPN + Mask RCNN
一条 SQL 的执行过程
随机推荐
《如何打一场数据挖掘赛事》入门版
Preparation of GL hsanps glycyrrhizic acid coupled human serum albumin loaded resveratrol / Rhein phospholipid complex serum protein nanoparticles
ES6类的继承
Android 面试题:为什么 Activity 都重建了 ViewModel 还存在?—— Jetpack 系列(3)
歪唱《七里香》——致敬杰伦
Kibana index pattern data search
Redis cluster setup (one master, two slave and three sentinels) complete version with verification report
C language structure
NFT:如何改进可租赁的NFT (ERC-4907)
Prometheus Operator 配置PrometheusRule告警规则
ES6中的拓展运算符
ceres-solver1.14版本与Eigen3.2.9版本
MySQL基础——数据库索引与事务
【Qt】解决 Qt console 输出中文乱码问题
R语言游程检验:使用runs.test函数对二值序列数据执行游程检验(检验序列是否是随机的)
Leetcode daily practice - 17.04 Vanishing numbers
木犀草素甘草酸共轭牛血清白蛋白纳米粒/牛血清白蛋白包覆紫杉醇脂质纳米粒的研究制备
【软件测试】—— 微信发红包测试用例
ES6函数参数默认值,以及rest参数
权限系统就该这么设计,yyds