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?
The second one creates a new array of Integers (first pass), and then adds all the elements of this new array to the list (second pass). It will thus be less efficient than the first one, which makes a single pass and doesn't create an unnecessary array of Integers.
A better way to use streams would be
List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());
Which should have roughly the same performance as the first one.
Note that for such a small array, there won't be any significant difference. You should try to write correct, readable, maintainable code instead of focusing on performance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With