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

Java中获取列表非空字符串索引并添加至集合报错问题

问题修复:将非空字符串索引添加到集合

原代码问题分析

你这段代码报错的核心原因是:IntStream是基本类型int的流,不能直接强制转换为Collection<? extends Integer>——IntStream本身并非Collection的子类,强制转换会抛出ClassCastException。同时,基本类型流需要先装箱为包装类型Integer的流,才能转换为集合类。

正确写法

方法1:装箱后收集为集合再添加

columnNum.addAll(IntStream.range(0, row.size())
    .filter(i -> StringUtils.isNotEmpty(row.get(i)))
    .boxed() // 将int类型流转换为Integer类型的Stream<Integer>
    .collect(Collectors.toList())); // 收集为List<Integer>(属于Collection子类)

方法2:直接遍历流添加到集合(更高效)

如果不想额外创建中间List,可以直接通过forEach将元素添加到集合:

IntStream.range(0, row.size())
    .filter(i -> StringUtils.isNotEmpty(row.get(i)))
    .boxed()
    .forEach(columnNum::add); // 直接将每个Integer元素添加到集合

方法3:直接收集为目标集合(新建集合场景)

如果columnNum是新建的集合,也可以一步到位:

// 假设columnNum是Set<Integer>
Set<Integer> columnNum = IntStream.range(0, row.size())
    .filter(i -> StringUtils.isNotEmpty(row.get(i)))
    .boxed()
    .collect(Collectors.toSet());

关键说明

  • boxed():必须调用这个方法,把IntStream(基本类型流)转换为Stream<Integer>(包装类型流),这样后续才能处理为集合类。
  • collect(Collectors.toList()):将流转换为List<Integer>,而List是Collection的子类,符合addAll()方法的参数要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:46:19