浏览了[墨三十一] 的JDK8函数式接口之UnaryOperator 文章后编写
前言
UnaryOperator继承了Funtion ,都可以链式函数操作,区别是Funtion是参数类型和返回值可以不一致,可以理解为二元的,而 UnaryOperator是一元的,代表返回值和参数类型一致。它们都有一个静态的identity方法,开发过程中我们一般使用它去指代流过程中的上一个对象本身,表示这一步的入参和返回值一致t -> t,为什么jdk要在两个函数式接口中都存放这样一个静态方法?
PS :
unary : 一元的
banary : 二元的
Function中的identity
UnaryOperator中的identity
英文的注释一致
测试代码
// UnaryOperator 是结果类型和参数类型一致的一元操作!!!!!
UnaryOperator<String> identity = UnaryOperator.identity();
// 这个就是开发过程中,如果使用 lambda表达式,需要用到对象本身的时候,跟function 中的 identity 区分的
// 因为 Function.identity() 可以参数和返回值不同,只要指定 T 和 R 一致,就可以作为表示对象本身的一元操作,而 UnaryOperator.identity() 本身就是 一元的
// 我们测试下这个的使用
List<User> userList = Stream.of(new User("123", "tom")).collect(Collectors.toList());
Map<String, User> collect1 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Map<String, User> collect2 = userList.stream().collect(Collectors.toMap(User::getId, UnaryOperator.identity()));
collect1.forEach((key, value) -> Logger.info(key + ":" + value));
collect2.forEach((key, value) -> Logger.info(key + ":" + value));
// 总结, 既可以使用 UnaryOperator 也可以使用 Function,这是一个显示的描述,函数式嘛,至于如何执行还要看最后的操作
执行结果
[main|TestUnaryOperator.lambda$main$2] |> 123:User{id='123', fullName='tom', age=null, agent='null', firstName='null', lastName='null'}
[main|TestUnaryOperator.lambda$main$3] |> 123:User{id='123', fullName='tom', age=null, agent='null', firstName='null', lastName='null'}
总结
- 流中表示没有任何操作的时候,既可以使用
UnaryOperator.identity()也可以使用Function.Identity()。 Function.Identity()是手动指定一个入参和出参可以不同的方法的参数和返回值一致的一元操作UnaryOperator.identity()是真正意义上的参数与返回值必须一致的一元操作。