【机试题】编写一个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;
    }
}
相关推荐
aXin_ya7 分钟前
微服务 第十天 (Redis多级缓存)
java·redis·微服务
逸Y 仙X22 分钟前
文章二十五:ElasticSearch 分页查询
java·大数据·数据库·elasticsearch·搜索引擎·全文检索
今天长肉了吗24 分钟前
风控指标平台实战:大数据量下如何设计分批处理
开发语言·数据库·python
ch.ju34 分钟前
Java programming(The third edition) Chapter Two——Null return value
java·开发语言
1.14(java)1 小时前
Spring事务和事务传播机制
java·数据库·spring
AI人工智能+电脑小能手1 小时前
【大白话说Java面试题】【Java基础篇】第34题:String、StringBuffer和StringBuilder的区别是什么
java·后端·面试
晓庆的故事簿1 小时前
JAVA搭配RabbitMQ使用
java·rabbitmq·java-rabbitmq
折哥的程序人生 · 物流技术专研1 小时前
第3篇:为何要配置环境变量?
java·开发语言·后端·面试
游乐码1 小时前
c#迭代器
开发语言·c#
渔民小镇1 小时前
4 行代码接入 Spring —— ionet 的生态融合之道
java·服务器·分布式·游戏