收集 IntStream 映射时出错 [英] Error when collecting IntStream to map

查看:42
本文介绍了收集 IntStream 映射时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码

String[] values = ...
.... 
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < values.length; i++) {
    map.put("X" + i, values[i]);
}

被 IntelliJ 转换为:

is converted by IntelliJ to:

Map<String, Object> map = IntStream.range(0, values.length)
        .collect(Collectors.toMap(
                i -> "X" + i,
                i -> values[i],
                (a, b) -> b));

可以缩短为

Map<String, Object> map = IntStream.range(0, values.length)
            .collect(Collectors.toMap(
                    i -> "X" + i,
                    i -> values[i]));

两个流版本无法编译.

IntelliJ,提示 values[i] 中的 i 存在问题:

IntelliJ, hints that there is an issue with the i in values[i]:

不兼容的类型.
必需:int
找到:java.lang.Object

Incompatible types.
Required: int
Found: java.lang.Object

编译器抱怨:

Error:(35, 17) java: 接口 java.util.stream.IntStream 中的方法 collect 不能应用于给定的类型;
需要:java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer
找到:java.util.stream.Collector>
原因:无法推断类型变量 R
(实际和形式参数列表的长度不同)

Error:(35, 17) java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier,java.util.function.ObjIntConsumer,java.util.function.BiConsumer
found: java.util.stream.Collector>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)

谁能解释一下为什么?

推荐答案

不太确定 intelliJ 的建议如何在那里工作,似乎不一致.只需放一个

Not very certain about how intelliJ's suggestion would work there, it seems inconsistent. Just put a

System.out.print(map);

声明和循环之间的语句,然后它不会建议你用 collect 替换.

statement between the declaration and loop and then it won't suggest you Replace with collect any further.

在使用 IntStream#collect 时,编译失败,原因是 collect 方法期望三个指定的参数在错误中也是可见的,而

While using the IntStream#collect, the compilation fails for the reason that implementation of collect method expects three specified arguments as visible in the error as well while the

Collectors.toMap(i -> "X" + i, i -> values[i])

只会产生一个 Collector 类型的参数.

would result in only a single argument of type Collector.

转换表达式的更好方法是

Better way to convert the expression would be though to

  • 要么使用forEach

Map<String, Object> map;
IntStream.range(0, values.length).forEach(i -> map.put("X" + i, values[i]));

  • 或者使用boxed()IntStream 转换为 Stream 为:-

    Map<String, Object> map = IntStream.range(0, values.length).boxed()
               .collect(Collectors.toMap(i -> "X" + i, i -> values[i], (a, b) -> b));
    

  • 或者按照@Holger 的建议,您可以避免使用 forEach 和装箱开销并修改构造以使用 IntStream.collect 三参数变体:-

    Map<String, Object> map = IntStream.range(0, values.length)
               .collect(HashMap::new, (m,i) -> m.put("X"+i,values[i]), Map::putAll);
    

  • 这篇关于收集 IntStream 映射时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆