Java 使用Consumer接口实现分页功能

public class HandlePage {
    
    

    public static void main(String[] args) {
    
    
        /**
         * 传入总条数和每页页数计算每页起始条数和结束条数
         * TriConsumer接口是重写的,可以以此分页功能为参考,自己重写Consumer接口实现别的功能
         */
        handleAsPage(3000, 100, null, (data, start, end) -> {
    
    
            System.out.println("start = [" + start + "] - end = [" + end + "]");
            /**
             * 此处写业务逻辑处理 
             */
        });
    }

    /**
     * 分页
     * @param total 总条数
     * @param pageSize 每页展示条数
     * @param data 需处理数据
     * @param consumer
     */
    private static void handleAsPage(int total, int pageSize, Object data, TriConsumer<Object, Integer, Integer> consumer) {
    
    
        if (total < 0 || pageSize <0 || null == consumer) {
    
    
            throw new IllegalArgumentException("Parameter(totalCount, pageSize) should be equals or grant than 0, and Parameter(consumer) should not be null");
        }

        int loopCount = total / pageSize;
        int begin = 1;
        for (int i = 0; i < loopCount; i++) {
    
    
            int end = begin + pageSize - 1;
            consumer.accept(data, begin, end);
            begin = begin + pageSize;
        }

        if (total % pageSize != 0) {
    
    
            // 截止条数越界处理,截止条数(end)计算方法可能会出现比总条数多1的情况(若SQL不严谨,可能会导致将不符合条件的数据处理掉)
            int end = (begin + total % pageSize) > total ? total : begin + total % pageSize;
            consumer.accept(data, begin, end);
        }
    }
}

// 重写TriConsumer接口,这里懒得引用log4j-api.jar所以重写了,不想写可以添加jar包依赖后使用
public interface TriConsumer<K, V, S> {
    
    
    void accept(K var1, V var2, S var3);
}

猜你喜欢

转载自blog.csdn.net/zhangwenchao0814/article/details/109314945