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<>()));
Thanks to Stack Community answers I can add some addons to question completeness for new readers:
As many pointed out, .boxed()
IntStream method is defined as:
@Override
public final Stream<Integer> boxed() {
return mapToObj(Integer::valueOf);
}
What basically re-defines issue to which one of following is better:
.mapToObj(in -> new Integer(in))
or
.mapToObj(in -> Integer.valueOf(in))
Yes, boxed()
uses Integer.valueOf
which can retrieve some Integer
instances from a cache.
So you should either use the version with boxed()
(preferably), or use Integer.valueOf
instead of new Integer()
. Note that boxed()
is in fact shorthand for mapToObj(Integer::valueOf)
.