【机试题】编写一个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;
    }
}
相关推荐
我登哥MVP20 小时前
SpringCloud 核心组件解析:分布式配置管理
java·spring boot·分布式·spring·spring cloud·java-ee·maven
lihao lihao20 小时前
linux线程
java·开发语言·jvm
满怀冰雪20 小时前
第13篇-栈算法入门-括号匹配-表达式与单调栈基础
java·算法
我是一颗柠檬20 小时前
【Java项目技术亮点】Redis Lua脚本原子化操作:高并发场景下的终极武器
java·redis·lua
swg32132120 小时前
Redis实现主从选举
java·前端·redis
码云骑士20 小时前
03-Python可变对象与不可变对象(下)-深浅拷贝的底层真相
开发语言·python
Java 码思客20 小时前
【ElasticSearch 从入门到架构师】第6章_分词器与文本检索
java·elasticsearch
Flittly20 小时前
【AgentScope Java新手村系列】(6)Hook与Middleware
java·spring boot·笔记·spring·ai
向量引擎20 小时前
AI API 正在进入“请求生命周期治理”阶段:从模型迁移、Agent 接入到成本与安全排错的工程化方法
java·人工智能·python·aigc·ai编程·ai写作·gpu算力