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());
}
相关推荐
Jamesvalley1 分钟前
【Django】新增字段后兼容旧接口 This field is required
后端·python·django
triticale5 分钟前
【蓝桥杯】P12165 [蓝桥杯 2025 省 C/Java A] 最短距离
java·蓝桥杯
Felven5 分钟前
A. Ideal Generator
java·数据结构·算法
秋野酱13 分钟前
基于 Spring Boot 的银行柜台管理系统设计与实现(源码+文档+部署讲解)
java·spring boot·后端
JAVA学习通27 分钟前
JAVA多线程(8.0)
java·开发语言
不当菜虚困30 分钟前
JAVA设计模式——(七)代理模式
java·设计模式·代理模式
Luck_ff081030 分钟前
【Python爬虫详解】第四篇:使用解析库提取网页数据——BeautifuSoup
开发语言·爬虫·python
学渣6765637 分钟前
什么时候使用Python 虚拟环境(venv)而不用conda
开发语言·python·conda
joke_xiaoli39 分钟前
tomcat Server 连接服务器 进展
java·服务器·tomcat
陶然同学1 小时前
RabbitMQ全栈实践手册:从零搭建消息中间件到SpringAMQP高阶玩法
java·分布式·学习·rabbitmq·mq