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(
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.