UnaryOperator汇总
Posted 郭慕荣博客园
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UnaryOperator汇总相关的知识,希望对你有一定的参考价值。
package com.example.springstudy.test.functions; import cn.hutool.core.util.ReflectUtil; import com.example.springstudy.test.User; import com.google.common.collect.Lists; import java.lang.reflect.Field; import java.util.List; import java.util.Optional; import java.util.UUID; import java.util.function.UnaryOperator; /** * @Author: guodong * @CreateTime: 2023-05-05 16:57 * @Description: TODO * @Version: 1.0 */ public class UnaryOperatorTest // 提供数据 public <T> void supplyData(Class<T> tClass, UnaryOperator<List<T>> unaryOperator) throws Exception List<T> userList = Lists.newArrayList(); for (int i = 1; i <= 10; i++) T entityNew = (T) ReflectUtil.newInstance(tClass); Field[] entityNewFields = ReflectUtil.getFields(entityNew.getClass()); for (Field field : entityNewFields) field.setAccessible(true); if (field.getName().equals("id")) field.set(entityNew, Long.valueOf(i)); else if (field.getName().equals("age")) field.set(entityNew, i); else if (field.getName().equals("name")) field.set(entityNew, UUID.randomUUID().toString()); userList.add(entityNew); unaryOperator.apply(userList); // 处理逻辑 public void handleData() throws Exception Optional<User> optionalUser = Optional.of(new User()); supplyData(User.class, list -> saveUserInfo(list); return null; ); // 保存数据 public void saveUserInfo(List<User> userList) userList.stream().forEach(data -> System.out.println(data)); public static void main(String[] args) throws Exception UnaryOperatorTest unaryOperatorTest = new UnaryOperatorTest(); unaryOperatorTest.handleData();
郭慕荣博客园
UnaryOperator函数式接口
这是一个函数式接口,因此可以用作lambda表达式或方法引用的赋值目标。
可以看到UnaryOperator<T>继承了Function<T,T>接口,这里可是两个T,T,还增加了static修饰的identity()方法。
然后我们写一个demo看看,实现的还是继承apply,只是不太明白这样的写法,接口继承从两个参数变成一个参数??
输出:
然后我们看LongUnaryOperator,IntUnaryOperator,DoubleUnaryOperator就没继承什么接口,这个就好容易理解了,针对这三种类型的特殊处理。
我们聊些有趣的事情
别把气氛弄的如此低沉
我知道这几天你心烦
每个人的活都不简单
以上是关于UnaryOperator汇总的主要内容,如果未能解决你的问题,请参考以下文章