Convert int stream to map

不羁岁月 提交于 2020-12-25 07:01:31

问题


I have an int stream and want for each element of that stream to do some calculations and return them as Map where keys are int values and values are result of that computations. I wrote following piece of code:

IntStream.range(0,10).collect(Collectors.toMap(Function.identity(), i -> computeSmth(i)));

where computeSmth(Integer a). I got next compiler error

 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)

What I'm doing wrong?


回答1:


Here is my code, it will work for you.

Function Reference version

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 expression version

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);
    }
}


来源:https://stackoverflow.com/questions/38318181/convert-int-stream-to-map

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!