You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java Stream将Book列表转为按读者分组的借阅书籍计数Map

嘿,我来帮你把这段Stream代码补全!你已经走对了前两步:筛选出已借出的书籍,然后提取出对应的读者信息,接下来只需要完成分组统计的逻辑就行啦。

首先,我们的目标是把每个读者和他持有的书籍数量对应起来,Java Stream的Collectors工具类正好有现成的分组和计数方法。这里有两种常用的实现方式,都能达到你的需求:

方式一:用counting()转换类型

counting()方法返回的是Long类型,我们可以用collectingAndThen把它转成Integer:

import java.util.function.Function;
import java.util.stream.Collectors;

// 完整代码
Map<String, Integer> readers = bookRepository.getAllBooks().stream()
    .filter(Book::getState) // 筛选出已借出的书籍(state为true表示已借出)
    .map(Book::getLastReader) // 提取每个已借出书籍的读者
    .collect(Collectors.groupingBy(
        Function.identity(), // 以读者名称作为Map的键
        Collectors.collectingAndThen(Collectors.counting(), Long::intValue) // 统计数量并转成Integer
    ));

方式二:用summingInt()直接得到Integer

如果不想做类型转换,可以用summingInt,每遇到一个读者就累加1,结果直接是Integer类型:

import java.util.function.Function;
import java.util.stream.Collectors;

// 完整代码
Map<String, Integer> readers = bookRepository.getAllBooks().stream()
    .filter(Book::getState)
    .map(Book::getLastReader)
    .collect(Collectors.groupingBy(
        Function.identity(),
        Collectors.summingInt(reader -> 1) // 每出现一次该读者,计数加1
    ));

额外提示:处理null情况

如果你的reader字段可能为null,建议在filter阶段加上null检查,避免Map出现null键:

.filter(book -> book.getState() != null && book.getState() && book.getLastReader() != null)

这样就能完美得到你想要的Map<String, Integer>啦!

内容的提问来源于stack exchange,提问作者steve1337

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:59:15