【机试题】编写一个Java函数,实现批量获取数据的功能

题目:编写一个Java函数,实现批量获取数据的功能(BService.get(List ids))。具体要求如下:

1)提供一个函数BService.get(List ids),支持最多传入100个id;

2)在BService.get((List ids)函数内部,需要将传入的id列表分批(每批10个id)进行调用AService.get(List ids)函数获取数据;

3)BService.get((List ids)函数需要返回所有批次获取的数据的合并结果,即一个包含所有数据的List;

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

public class BService {
    private AService aService;

    public BService(AService aService) {
        this.aService = aService;
    }

    public List<Integer> get(List<Integer> ids) {
        List<Integer> result = new ArrayList<>();
        if (ids == null || ids.size() == 0) {
            return result;
        }
        int batchSize = 10;
        int batchCount = (ids.size() + batchSize - 1) / batchSize;
        for (int i = 0; i < batchCount; i++) {
            int start = i * batchSize;
            int end = Math.min(start + batchSize, ids.size());
            List<Integer> batchIds = ids.subList(start, end);
            List<Integer> batchResult = aService.get(batchIds);
            result.addAll(batchResult);
        }
        return result;
    }
}
相关推荐
014-code3 小时前
订单超时取消与库存回滚的完整实现(延迟任务 + 状态机)
java·开发语言
lly2024064 小时前
组合模式(Composite Pattern)
开发语言
游乐码4 小时前
c#泛型约束
开发语言·c#
Dontla4 小时前
go语言Windows安装教程(安装go安装Golang安装)(GOPATH、Go Modules)
开发语言·windows·golang
chushiyunen4 小时前
python rest请求、requests
开发语言·python
铁东博客4 小时前
Go实现周易大衍筮法三变取爻
开发语言·后端·golang
baidu_huihui4 小时前
在 CentOS 9 上安装 pip(Python 的包管理工具)
开发语言·python·pip
南 阳4 小时前
Python从入门到精通day63
开发语言·python
lbb 小魔仙4 小时前
Python_RAG知识库问答系统实战指南
开发语言·python
java1234_小锋4 小时前
Java高频面试题:Springboot的自动配置原理?
java·spring boot·面试