英文:
Value insertion into list using JAVA 8
问题
public static void main(String[] args) {
List<Long> list = new ArrayList<>();
for (long i = 1; i < 100000000; i++) {
list.add(i);
}
}
这个循环花费了太长时间来向列表中插入值,是否有Java 8中的一些特性,可以在更短的时间内执行相同的任务。
英文:
public static void main(String[] args) {
List<Long> list = new ArrayList<>();
for (long i = 1; i < 100000000; i++) {
list.add(i);
}
}
this loop taking too long to insert values into the list is there any features in JAVA 8, using that the same task will perform in a minimal time.
答案1
得分: 0
如果不强制要求列表为 `ArrayList`:
Long[] array = new Long[100_000_000];
Arrays.parallelSetAll(array, Long::valueOf);
List<Long> list = Arrays.asList(array);
我没有进行任何时间测量。列表将是可修改的,您可以设置值,但它具有固定的大小,不能添加或删除。
如果您确实需要一个可变大小的列表,可以尝试:
List<Long> list = new ArrayList(Arrays.asList(array));
然而,这在某种程度上违反了利用并行执行的想法,我不再确定速度如何与您已经获得的内容相比。
编辑:如果列表根本不需要是可修改的,可以创建自己的“列表”实现,它不存储任何实际数据,并在每次请求元素时计算值。然后初始化将不需要时间。您可以为此目的子类化 `AbstractList`。
英文:
If it’s not mandatory that the list be an ArrayList
:
Long[] array = new Long[100_000_000];
Arrays.parallelSetAll(array, Long::valueOf);
List<Long> list = Arrays.asList(array);
I have not done any time measurements. The list will be modifiable in the sense that you can set values, but it has fixed size, there is no adding or removing.
If you do need a variable-size list, you may try:
List<Long> list = new ArrayList(Arrays.asList(array));
It somewhat defies the idea of exploiting parallel execution, though, and I am no longer sure about how the speed would compare to what you have already got.
Edit: If the list doesn’t need to be modifiable at all, make your own “list” implementation that doesn’t store any actual data and calculates the value each time an element is asked for. Then initialization will take no time. You can subclass AbstractList
for this purpose.
专注分享java语言的经验与见解,让所有开发者获益!
评论