java8函数式编程实例

Function、Consumer的使用

废话不多说,直接上代码:

public class FunctionPageUtils {

    FunctionPageUtils() {}

    /**
     * 自定义函数:参数*10
     * 参数:Integer
     * 返回:Integer
     */
    private static Function<Integer,Integer> action = action -> action * 10;

    /**
     * 自定义函数:+1操作,无返回值
     * 参数:Integer
     */
    private static Consumer<Integer> consumer = consumer -> {
        consumer+=1;
        System.out.println(consumer);
    };

    public static void main(String[] args) {
        Integer apply = action.apply(10);
        System.out.println(apply);
        consumer.accept(apply);

        FunctionPageUtils.dealPageFunction(num->{
            // 假设固定每次取10个值
            return getData((num - 1) * 10, num * 10);
        },t->{
            // 这里可以做一些复杂操作
            System.out.println(",,,"+t);
        });
    }

    /**
     * 制造一些假数据:模拟分页查数据库数据
     * @param num 相当于页数
     * @param pageSize 相当于分页大小
     * @return
     */
    private static List<String> getData(Integer num, Integer pageSize) {
        List<String> list = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            list.add(i+",,,");
        }
        // 因为查的不是数据库,会出现下标越界情况
        try {
            return list.subList(num,pageSize);
        }catch (Exception e) {
            return null;
        }
    }

    /**
     * 分页获取和处理数据
     * @param param 函数式参数:param是函数式返回的结果,类型是List<T>
     * @param consumer 函数式参数
     * @param <T>
     */
    public static <T> void  dealPageFunction(Function<Integer,List<T>> param, Consumer<T> consumer) {

        Integer num = 1;
        // 调用自定义函数,传参获取集合
        List<T> result = param.apply(num);

        while (true) {
            if(result == null) {
                break;
            }
            for (T t : result) {
                if(t == null) {
                    continue;
                }
                consumer.accept(t);
            }

            num ++;
            result = param.apply(num);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值