将int流转换为地图 [英] Convert int stream to map

查看:88
本文介绍了将int流转换为地图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

其中computeSmth(Integer a).我遇到下一个编译器错误

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)

我做错了什么?

推荐答案

这是我的代码,它将对您有用.

Here is my code, it will work for you.

功能参考版本

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

这篇关于将int流转换为地图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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