【机试题】编写一个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;
    }
}
相关推荐
唐青枫21 小时前
Java 虚拟线程实战指南:从 Thread API 到 Spring Boot 高并发应用
java
白鲸开源2 天前
Apache SeaTunnel Zeta Engine 的 Basic Auth 是怎么工作的?
java·vue.js·github
白鲸开源2 天前
一文读懂DolphinScheduler插件机制:如何轻松扩展任务类型与数据源
java·架构·github
用户298698530142 天前
Java 实现 Word 文档文本查找与高亮标注
java·后端
宇宙之一粟2 天前
乐企版式文件生成平台
java·后端·python
plainGeekDev2 天前
MVC 写法 → MVVM
android·java·kotlin
SL_staff2 天前
3周搭完MES系统:JVS低代码+JVS-IoT物联网的实战记录
java·前端·低代码
MacroZheng2 天前
斩获20w star!Claude Code最强插件,AI编程必备!
java·人工智能·后端
唐青枫2 天前
Java Spring WebFlux 实战指南:用 Mono、Flux 和 WebClient 写响应式接口
java·spring
小bo波2 天前
使用Thread子类创建线程 VS 使用Runnable接口创建线程的区别
java·多线程·thread·并发编程·runnable