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

Java Stream处理int数组转Map时%运算符无法应用于Object报错

问题说明

预期实现从int数组生成Map的功能,Map的键代表对应整数的位数,原始代码如下:

public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
    return Arrays.stream(x)  // array to stream
        .filter(n -> n >= 0) // filter negative numbers
        .collect(Collectors.groupingBy(n -> Integer.toString((Integer) n).length(), // group by number of digits
            Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d,
                Collectors.toList()))); // if even e odd o add to list
}

编译时在mapping()方法调用行抛出如下错误:

Operator '%' cannot be applied to 'java.lang.Object', 'int'

错误根因

Arrays.stream(int[])返回的是原始类型int专用的IntStream,这类原始类型流仅支持三参数的collect重载方法,不支持直接传入通用Collector作为入参。这种场景下编译器无法正确推导流元素的类型,会将groupingBy分类函数、mapping映射函数的入参统一识别为Object类型,自然无法对Object类型的变量使用%取模运算符和int做运算。

修复方法

在过滤逻辑后增加boxed()调用,将原始类型IntStream转换为包装类Integer的引用类型流Stream<Integer>,后续收集器的泛型类型就可以被正确推导,代码中手动添加的(Integer)强转也可以直接删除。
修复后的完整代码:

public static Map<Integer, List<String>> groupByDigitNumbersArray(int[] x) {
    return Arrays.stream(x)
        .filter(n -> n >= 0)
        .boxed() // 将原始int流转换为Integer引用流,解决泛型推导失败问题
        .collect(Collectors.groupingBy(n -> Integer.toString(n).length(),
            Collectors.mapping(d -> (d % 2 == 0 ? "e" : "o") + d,
                Collectors.toList())));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 02:01:34