Java 8 primitive stream to collection mapping methods

后端 未结 6 962
醉话见心
醉话见心 2021-01-13 10:22

Is there any significant difference (in performance or best practices) between those two stream creation methods?

int[] arr2 = {1,2,3,4,5,6};

Arrays.stream(         


        
6条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 10:42

    In terms of best practice, the second approach is preferable because when you want to box a primitive value boxed is created exactly for that purpose and does so in the most optimised way possible whereas mapToObj, although can be used to achieve the same thing, is not the idiomatic approach.

    Further, it's advised not to use the primitive wrapper type constructors anymore and instead favour the valueOf methods, this is because these constructors have been deprecated as well as the fact that by using the valueOf it reduces memory footprint compared to the constructors leading to better performance.

提交回复
热议问题