Converting Array to List

2020-02-03 05:03发布

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?

标签: arrays java-8
8条回答
Ridiculous、
2楼-- · 2020-02-03 05:46

If you are dealing with String[] instead of int[], We can use

ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));
查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-03 05:50

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.

查看更多
登录 后发表回答