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

JavaArraysPerformance

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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);
}

Solution 3 - Java

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.

Solution 4 - Java

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();

Solution 5 - Java

Use: Arrays.copyOf(yourArray,n);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJoelView Question on Stackoverflow
Solution 1 - Javasrc3369View Answer on Stackoverflow
Solution 2 - JavaElliott FrischView Answer on Stackoverflow
Solution 3 - JavaZhongYuView Answer on Stackoverflow
Solution 4 - JavaJack ColeView Answer on Stackoverflow
Solution 5 - Javauser2280949View Answer on Stackoverflow