Java 函数式接口BiConsumer

BiConsumer是一个函数式接口,代表一个接受两个输入参数且不返回任何内容的操作符

java 复制代码
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiConsumer;

public class BatchOperate<T> {
    private int batchSize=3000;
    private List<T> content=new ArrayList<>();
    private BiConsumer<Integer,List<T>> consumer;
    private int pageNo;
    private long total;

    public void setConsumer(BiConsumer<Integer,List<T>> consumer){
        this.consumer=consumer;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public void addBatch(T t){
        this.content.add(t);
        this.total++;
        if (content.size()>=batchSize){
            this.executeBatch();
        }
    }

    public long getTotal() {
        return total;
    }

    public void executeBatch() {
        if(this.content.size()>0){
            pageNo++;
            consumer.accept(this.pageNo,this.content);
            this.content=new ArrayList<>();
        }
    }

}

使用:

java 复制代码
private void processUser(){
	int size  = 1000;
	BatchOperate<User> batchOperate = new BatchOperate<>();
	batchOperate.setBatchSize(size);
	batchOperate.setConsumer((index, list) -> {
		log.info("######处理用户信息:{}", index);
		removeUserInfo(list);
	});

	for(int i=0; i < 9000; i++){ //生成用户放到 batchOperate
		User user = new User();
		batchOperate.addBatch(user);
	}
	batchOperate.executeBatch();
}


private void removeUserInfo(List<user> userList){
	//处理逻辑
	System.out.println(userList.size());
}
相关推荐
wuxuanok17 分钟前
SpringBoot -原理篇
java·spring boot·spring
柿蒂19 分钟前
从if-else和switch,聊聊“八股“的作用
android·java·kotlin
二饭21 分钟前
Spring Boot 项目启动报错:MongoSocketOpenException 连接被拒绝排查日记
java·spring boot·后端
Dxy123931021622 分钟前
python把文件从一个文件复制到另一个文件夹
开发语言·python
懒虫虫~39 分钟前
通过内存去重替换SQL中distinct,优化SQL查询效率
java·sql·慢sql治理
鼠鼠我捏,要死了捏43 分钟前
基于Redisson的分布式锁原理深度解析与性能优化实践指南
java·高并发·redisson
backordinary1 小时前
微服务学习笔记25版
java·java-ee
sonrisa_1 小时前
collections模块
python
折翼的恶魔1 小时前
数据分析:排序
python·数据分析·pandas
ZZHow10241 小时前
Maven入门_简介、安装与配置
java·笔记·maven