Java stream使用样例

1.Batch分批处理

假设批处理逻辑为打印批的各个元素:

private static void process(List<String> batch) {
        System.out.println(batch);
    }

一般,对集合分批处理会涉及计算批次数、逐批处理,如下:

/**
     * 基础for遍历方式
     *
     * @param records
     */
    private static void iterWay(List<String> records) {
        List<String> batch = new ArrayList<>();
        for (int index = 0, size = records.size(); index < size; index++) {
            batch.add(records.get(index));
            if (batch.size() == BATCH) {
                process(batch);
                batch.clear();
            }
        }
        // 最后一批
        if (batch.size() > 0) {
            process(batch);
        }

    }

使用stream可以更优雅地解决分批处理问题:

 /**
     * 使用stream方式
     *
     * @param records
     */
    private static void streamWay(List<String> records){
        IntStream.range(0, (records.size() + BATCH - 1) / BATCH)
                .mapToObj(i -> records.subList(i * BATCH, Math.min(records.size(), (i + 1) * BATCH)))
                .forEach(batch -> process(batch));
    }

简单测试一下:

public static void main(String[] args) {

        List<String> records = Stream.of("a", "b", "c", "d", "e").collect(Collectors.toList());

        // base way
        iterWay(records);

        // stream way
        streamWay(records);

    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容