Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 345
Joel Avatar asked Jul 09 '15 23:07

Joel


People also ask

How do you find the first three items of an array?

Use the Array. slice() method to get the first N elements of an array, e.g. const first3 = arr. slice(0, 3) . The slice() method will return a new array containing the first N elements of the original array.

How do I get the first element of a list?

The get() method of the ArrayList class accepts an integer representing the index value and, returns the element of the current ArrayList object at the specified index. Therefore, if you pass 0 to this method you can get the first element of the current ArrayList and, if you pass list.

What is the easiest way to add a new element to an array?

By using ArrayList as intermediate storage: Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.


2 Answers

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

like image 54
src3369 Avatar answered Sep 27 '22 17:09

src3369


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); } 
like image 29
Elliott Frisch Avatar answered Sep 27 '22 16:09

Elliott Frisch