将列表的前 n 个元素存储在数组中的最快方法是什么?
考虑到这个场景:
int n = 10;
ArrayList<String> in = new ArrayList<>();
for(int i = 0; i < (n+10); i++)
in.add("foobar");
选项 1:
String[] out = new String[n];
for(int i = 0; i< n; i++)
out[i]=in.get(i);
选项 2:
String[] out = (String[]) (in.subList(0, n)).toArray();
选项 3: 有更快的方法吗?也许使用 Java8 流?
最佳答案
假设:
列表 - 列表 <String>
使用 Java 8 流,
将列表中的前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]);
关于java - 将列表的第一个元素输入数组的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31330330/