转换数组列表 [英] Converting Array to List

查看:176
本文介绍了转换数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在为一个整数数组转换为整数的列表,我曾尝试以下方法:

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


  1. 初始化整数的列表,迭代这个数组并插入到列表

  1. Initialize an list of integer, iterate over the array and insert into list

通过使用Java 8流:

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.

使用流的更好的方式是

List<Integer> list = Arrays.stream(ints).boxed().collect(Collectors.toList());

哪个应具有大致相同的性能的第一个。

Which should have roughly the same performance as the first one.

请注意,对于这样的小阵列中,将不会有任何显著差异。你应该尝试写,而不是注重业绩正确后,可读,可维护code。

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.

这篇关于转换数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆