With streams added in Java 8 we can write code like:
int[] example1 = list.stream().mapToInt(i->i).toArray();
// OR
int[] example2 = list.stream().mapToInt(Integer::intValue).toArray();
Thought process:
-
The simple
Stream#toArrayreturns anObject[]array, so it is not what we want. Also,Stream#toArray(IntFunction<A[]> generator)doesn’t do what we want, because the generic typeAcan’t represent the primitive typeint -
So it would be nice to have some stream which could handle the primitive type
intinstead of the wrapperInteger, because itstoArraymethod will most likely also return anint[]array (returning something else likeObject[]or even boxedInteger[]would be unnatural here). And fortunately Java 8 has such a stream which isIntStream -
So now the only thing we need to figure out is how to convert our
Stream<Integer>(which will be returned fromlist.stream()) to that shinyIntStream.Quick searching in documentation of
Streamwhile looking for methods which returnIntStreampoints us to our solution which ismapToInt(ToIntFunction<? super T> mapper)method. All we need to do is provide a mapping fromIntegertoint.Since
ToIntFunctionis functional interface we can provide its instance via lambda or method reference.Anyway to convert Integer to int we can use
Integer#intValueso insidemapToIntwe can write:mapToInt( (Integer i) -> i.intValue() )(or some may prefer:
mapToInt(Integer::intValue).)But similar code can be generated using unboxing, since the compiler knows that the result of this lambda must be of type
int(the lambda used inmapToIntis an implementation of theToIntFunctioninterface which expects as body a method of type:int applyAsInt(T value)which is expected to return anint).So we can simply write:
mapToInt((Integer i)->i)Also, since the
Integertype in(Integer i)can be inferred by the compiler becauseList<Integer>#stream()returns aStream<Integer>, we can also skip it which leaves us withmapToInt(i -> i)