将IntStream转换为Map

31

我有一个IntStream,想要对该流的每个元素进行一些计算,并将它们作为Map返回,其中键是 int 值,值是计算结果。我编写了以下代码:


Map<Integer, Double> result = intStream
    .boxed()
    .collect(Collectors.toMap(Function.identity(), element -> {
        // calculation logic here
        return result;
    }));
IntStream.range(0,10)
    .collect(
        Collectors.toMap(Function.identity(), i -> computeSmth(i)));

当我调用 computeSmth(Integer a) 时,我得到了以下编译器错误。

method collect in interface java.util.stream.IntStream cannot be applied to given types;
 required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
 found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Map<java.lang.Object,java.lang.String>>
 reason: cannot infer type-variable(s) R
   (actual and formal argument lists differ in length)

我做错了什么?


11
IntStream 只有三个参数的 collect 方法。你需要将你的 toMap 方法改写为三个参数的形式,或者使用 .boxed()IntStream 转换为 Stream<Integer> - Misha
@Misha 谢谢,我刚学到了 boxed()。这肯定比 mapToObj(Integer::valueOf) 更好。 :-) - C. K. Young
1个回答

39

以下是我的代码,它可以为您工作。

功能参考版本

public class AppLauncher {

public static void main(String a[]){
    Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),AppLauncher::computeSmth));
    System.out.println(map);
}
  public static Integer computeSmth(Integer i){
    return i*i;
  }
}

lambda表达式版本

public class AppLauncher {

    public static void main(String a[]){
        Map<Integer,Integer> map = IntStream.range(1,10).boxed().collect(Collectors.toMap(Function.identity(),i->i*i));
        System.out.println(map);
    }
}

17
的确,boxed() 是成功的关键! - user1075613

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接