Java 8 primitive stream to collection mapping methods

  • A+
Category:Languages

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(arr2)     .map((in)->in*2)     .mapToObj((in) -> new Integer(in))     .collect(Collectors.toCollection(()-> new ArrayList<>()));      Arrays.stream(arr2)     .map(in->in*2)     .boxed()     .collect(Collectors.toCollection(()-> new ArrayList<>())); 

 


The second is better as it creates no Integer objects in this example.

From the JLS 5.1.7

If the value p being boxed is ... an int ... between -128 and 127 (inclusive), then let r1 and r2 be the results of any two boxing conversions of p. It is always the case that r1 == r2.

Generally speaking, you should not call new on wrapper types, but use their static factory methods - for example Integer.valueOf

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: