No one mentioned yet streams added in Java 8 so here it goes:
int[] array = list.stream().mapToInt(i->i).toArray();
Thought process:
- simple
Stream#toArray
returns Object[]
, so it is not what we want. Also Stream#toArray(IntFunction generator)
doesn't do what we want because generic type A
can't represent primitive int
- so it would be nice to have some stream which could handle primitive type
int
instead of wrapper Integer
, because its toArray
method will most likely also return int[]
array (returning something else like Object[]
or even boxed Integer[]
would be unnatural here). And fortunately Java 8 has such stream which is IntStream
so now only thing we need to figure out is how to convert our Stream
(which will be returned from list.stream()
) to that shiny IntStream
. Here Stream#mapToInt(ToIntFunction super T> mapper) method comes to a rescue. All we need to do is pass to it mapping from Integer
to int
. We could use something like Integer#getValue
which returns int
like :
mapToInt( (Integer i) -> i.intValue() )
(or if someone prefers mapToInt(Integer::intValue)
)
but similar code can be generated using unboxing, since compiler knows that result of this lambda must be int
(lambda in mapToInt
is implementation of ToIntFunction
interface which expects body for int applyAsInt(T value)
method which is expected to return int
).
So we can simply write
mapToInt((Integer i)->i)
Also since Integer
type in (Integer i)
can be inferred by compiler because List#stream()
returns Stream
we can also skip it which leaves us with
mapToInt(i -> i)