将List的前n个元素放入数组的最快方法 [英] Fastest way to get the first n elements of a List into an Array

查看:89
本文介绍了将List的前n个元素放入数组的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

将此视为场景:

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-streams?

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

推荐答案

选项1比选项2更快



因为选项2创建了一个新的 List 引用,然后从<$ c $创建一个 n 元素数组c> List (选项1完美地调整输出数组的大小)。但是,首先你需要修复一个bug。使用< (不是< = )。比如,

Option 1 Faster Than Option 2

Because Option 2 creates a new List reference, and then creates an n element 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,

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

这篇关于将List的前n个元素放入数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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