Java 将列表的前 n 个元素放入数组的最快方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31330330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 10:55:54  来源:igfitidea点击:

Fastest way to get the first n elements of a List into an Array

javaarraysperformance

提问by Joel

What is the fastest way to get the first n elements of a list stored in an array?

获取存储在数组中的列表的前 n 个元素的最快方法是什么?

Considering this as the scenario:

考虑到这个场景:

int n = 10;
ArrayList<String> in = new ArrayList<>();
for(int i = 0; i < (n+10); i++)
  in.add("foobar");

Option 1:

选项1:

String[] out = new String[n];
for(int i = 0; i< n; i++)
    out[i]=in.get(i);

Option 2:

选项 2:

String[] out = (String[]) (in.subList(0, n)).toArray();

Option 3:Is there a faster way? Maybe with Java8-streams?

选项 3:有没有更快的方法?也许使用 Java8 流?

采纳答案by Elliott Frisch

Option 1 Faster Than Option 2

选项 1 比选项 2 快

Because Option 2 creates a new Listreference, and then creates an nelement array from the List(option 1 perfectly sizes the output array). However, first you need to fix the off by one bug. Use <(not <=). Like,

因为选项 2 创建了一个新的List引用,然后nList(选项 1 完美地调整了输出数组的大小)创建了一个元素数组。但是,首先您需要通过一个错误修复关闭。使用<(不是<=)。喜欢,

String[] out = new String[n];
for(int i = 0; i < n; i++) {
    out[i] = in.get(i);
}

回答by ZhongYu

It mostly depends on how big nis.

这主要取决于有多大n

If n==0, nothing beats option#1 :)

如果n==0,没有什么比选项#1 更好的了 :)

If n is very large, toArray(new String[n])is faster.

如果 n 非常大,toArray(new String[n])则更快。

回答by src3369

Assumption:

假设:

list - List<String>

列表 - 列表<String>

Using Java 8 Streams,

使用 Java 8 流,

  • to get first N elements from a list into a list,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • to get first N elements from a list into an Array,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

  • 将列表中的前 N ​​个元素放入列表中,

    List<String> firstNElementsList = list.stream().limit(n).collect(Collectors.toList());

  • 将列表中的前 N ​​个元素放入数组中,

    String[] firstNElementsArray = list.stream().limit(n).collect(Collectors.toList()).toArray(new String[n]);

回答by user2280949

Use: Arrays.copyOf(yourArray,n);

使用:Arrays.copyOf(yourArray,n);