Java 8 primitive stream to collection mapping methods

后端 未结 6 993
醉话见心
醉话见心 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条回答
  •  Happy的楠姐
    2021-01-13 11:05

    For both performance and best practices, we should choose boxed() over mapToObj((in) -> new Integer(in)).


    Performance:

    See below boxed() source code (in the abstract class IntPipeline which implements IntStream, in the package java.util.stream ):

    @Override
        public final Stream boxed() {
            return mapToObj(Integer::valueOf);
        }
    

    So it is calling mapToObj() with Integer::valueOf. Note that by reusing cached values,Integer::valueOf is more efficient than new Integer() , so we should choose boxed().


    Best practice:

    Besides the performance difference, with boxed() we write less, and it is easier to read.

提交回复
热议问题