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

Java 8如何从BigQuery返回的对象列表中提取ID并生成新列表

Java 8 从对象列表提取ID到新列表的正确实现

你的代码核心问题是误用了Collectors.groupingBy,这个方法返回的是Map<ID类型, List>(按ID分组后的对象集合),根本不是List,强行类型转换必然报错。另外你目标是List<String>,还需要注意ID类型的转换。

正确实现代码

假设ItemData的getId()返回Integer类型(对应示例里的数字ID),正确写法如下:

List<String> itemList = bqList.stream()
    .filter(entity -> entity.getId() != null)
    .map(entity -> String.valueOf(entity.getId())) // 将数字ID转为String
    .collect(Collectors.toList());

如果getId()本身返回的就是String类型,简化为:

List<String> itemList = bqList.stream()
    .filter(entity -> entity.getId() != null)
    .map(ItemData::getId)
    .collect(Collectors.toList());

逻辑说明

  • filter:保留ID不为null的对象,和你原逻辑一致
  • map:将每个ItemData对象转换为对应的ID值,并按需转成String类型,匹配目标列表的泛型
  • collect(Collectors.toList()):将流转为List集合,无需任何强制类型转换

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 21:22:07