Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array to List

Tags:

arrays

java-8

In order to convert an Integer array to a list of integer I have tried the following approaches:

  1. Initialize a list(Integer type), iterate over the array and insert into the list

  2. 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?

like image 517
Jobs Avatar asked May 08 '15 11:05

Jobs


1 Answers

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.

like image 172
JB Nizet Avatar answered Sep 29 '22 23:09

JB Nizet