美文网首页
Java stream使用样例

Java stream使用样例

作者: 西瓜雪梨桔子汁 | 来源:发表于2023-03-06 22:42 被阅读0次

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);

    }

相关文章

网友评论

      本文标题:Java stream使用样例

      本文链接:https://www.haomeiwen.com/subject/zjrvldtx.html