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<>()));
EDIT
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))
.mapToObj((in) -> Integer.valueOf(in*2))
– Brubecknew Integer
, alwaysInteger.valueOf
. Beside, useCollectors.toList()
. For the rest, write a benchmark. – Certainnew Integer(int x)
is as wellDeprecated
since Java9. So just avoid using it. – Tissue