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

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?

This question is related to java arrays performance

The answer is


Use: Arrays.copyOf(yourArray,n);


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.


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

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


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to performance

Why is 2 * (i * i) faster than 2 * i * i in Java? What is the difference between spark.sql.shuffle.partitions and spark.default.parallelism? How to check if a key exists in Json Object and get its value Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly? Most efficient way to map function over numpy array The most efficient way to remove first N elements in a list? Fastest way to get the first n elements of a List into an Array Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3? pandas loc vs. iloc vs. at vs. iat? Android Recyclerview vs ListView with Viewholder