Error when collecting IntStream to map

后端 未结 1 688
梦如初夏
梦如初夏 2021-01-18 05:29

The following code

String[] values = ...
.... 
Map map = new HashMap<>();
for (int i = 0; i < values.length; i++) {
    map.pu         


        
相关标签:
1条回答
  • 2021-01-18 05:57

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

    System.out.print(map);
    

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


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

    would result in only a single argument of type Collector.


    Better way to convert the expression would be though to

    • either use forEach

      Map<String, Object> map;
      IntStream.range(0, values.length).forEach(i -> map.put("X" + i, values[i]));
      
    • Or use boxed() to convert the IntStream to Stream<Integer> as:-

      Map<String, Object> map = IntStream.range(0, values.length).boxed()
                 .collect(Collectors.toMap(i -> "X" + i, i -> values[i], (a, b) -> b));
      
    • Or as suggested by @Holger, you can avoid using forEach and boxing overhead and modify the construct to make use of the IntStream.collect three-arg variant as:-

      Map<String, Object> map = IntStream.range(0, values.length)
                 .collect(HashMap::new, (m,i) -> m.put("X"+i,values[i]), Map::putAll);
      
    0 讨论(0)
提交回复
热议问题