【机试题】编写一个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;
    }
}
相关推荐
刘一说14 小时前
Spring Boot中IoC(控制反转)深度解析:从实现机制到项目实战
java·spring boot·后端
悟空码字14 小时前
SpringBoot参数配置:一场“我说了算”的奇幻之旅
java·spring boot·后端
我居然是兔子14 小时前
Java虚拟机(JVM)内存模型与垃圾回收全解析
java·开发语言·jvm
关于不上作者榜就原神启动那件事14 小时前
Spring Data Redis 中的 opsFor 方法详解
java·redis·spring
其美杰布-富贵-李14 小时前
Java (Spring Boot) 反射完整学习笔记
java·spring boot·学习
小许好楠14 小时前
java开发工程师-学习方式
java·开发语言·学习
superman超哥14 小时前
仓颉锁竞争优化深度解析
c语言·开发语言·c++·python·仓颉
Halo_tjn14 小时前
基于 IO 流实现文件操作的专项实验
java·开发语言
一晌小贪欢14 小时前
【Python办公自动化】Python办公自动化常用库新手指南
开发语言·python·python自动化办公·python3·python办公自动化·python办公
姓蔡小朋友15 小时前
MySQL事务、InnoDB存储引擎
java·数据库·mysql