72

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

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:

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

Option 2:

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

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

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
Joel
  • 1,725
  • 3
  • 16
  • 34

7 Answers7

142

Assumption:

list - List<String>

Using Java 8 Streams,

  • 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]);

src3369
  • 1,839
  • 2
  • 17
  • 18
12

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
3

It mostly depends on how big n is.

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

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

ZhongYu
  • 19,446
  • 5
  • 33
  • 61
1

Option 3

Iterators are faster than using the get operation, since the get operation has to start from the beginning if it has to do some traversal. It probably wouldn't make a difference in an ArrayList, but other data structures could see a noticeable speed difference. This is also compatible with things that aren't lists, like sets.

String[] out = new String[n];
Iterator<String> iterator = in.iterator();
for (int i = 0; i < n && iterator.hasNext(); i++)
    out[i] = iterator.next();
Jack Cole
  • 1,528
  • 2
  • 19
  • 41
0

Use .take(n) operator on your list

FarVoyager
  • 49
  • 4
  • Can you please explain in detail which method you mean? In the [List interface](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/List.html) there is no method called like this. – vanje Jul 29 '22 at 16:23
  • 1
    This can be a comment – Jimale Abdi Jul 31 '22 at 07:16
  • @vanje looks like this extension is only available on kotlin, sorry for confusing. However I would like this answer to be here because I being a kotlin user ended up here in search of this function. So other kotlin users can come to this topic and get the answer – FarVoyager Aug 02 '22 at 13:11
0
arrayList.stream().limit(n).toArray();

n = maxSize in length

This will help you to get the max size of the Array that you require.

toyota Supra
  • 3,181
  • 4
  • 15
  • 19
-6

Use: Arrays.copyOf(yourArray,n);