Convert int stream to map

后端 未结 1 927
耶瑟儿~
耶瑟儿~ 2021-01-07 20:42

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 computat

1条回答
  •  伪装坚强ぢ
    2021-01-07 21:10

    Here is my code, it will work for you.

    Function Reference version

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

    0 讨论(0)
提交回复
热议问题