In order to convert an Integer array to a list of integer I have tried the following approaches:
Initialize a list(Integer type), iterate over the array and insert into the list
By using Java 8 Streams:
int[] ints = {1, 2, 3}; List<Integer> list = new ArrayList<Integer>(); Collections.addAll(list, Arrays.stream(ints).boxed().toArray(Integer[]::new));
Which is better in terms of performance?
Simply try something like
Old way but still working!
If you don't mind a third-party dependency, you could use a library which natively supports primitive collections like Eclipse Collections and avoid the boxing altogether. You can also use primitive collections to create boxed regular collections if you need to.
If you want the boxed collection in the end, this is what the code for
collect
onIntArrayList
is doing under the covers:Since the question was specifically about performance, I wrote some JMH benchmarks using your solutions, the most voted answer and the primitive and boxed versions of Eclipse Collections.
These are the results from these tests on my Mac Book Pro. The units are operations per second, so the bigger the number, the better. I used an
ImmutableIntList
for theecPrimitive
benchmark, because theMutableIntList
in Eclipse Collections doesn't copy the array by default. It merely adapts the array you give it. This was reporting even larger numbers forecPrimitive
, with a very large margin of error because it was essentially measuring the cost of a single object creation.If anyone spots any issues with the benchmarks, I'll be happy to make corrections and run them again.
Note: I am a committer for Eclipse Collections.
If you don't want to alter the list:
But if you want to modify it then you can use this:
Or just use java8 like the following:
Java9 has introduced this method:
However, this will return an immutable list that you can't add to.
You need to do the following to make it mutable:
where stateb is List'' bucket is a two dimensional array
statesb= IntStream.of(bucket[j-1]).boxed().collect(Collectors.toList());
with import java.util.stream.IntStream;
see https://examples.javacodegeeks.com/core-java/java8-convert-array-list-example/
This basically does 1 (iterate over the array) with 2 (using Java 8). (with 1 and 2 referring to your original question)