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

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

To get the first n elements of a List into an array in Java, you can use the List.subList() method to create a sublist containing the first n elements and then convert that sublist to an array. Here's how you can do it:

import java.util.ArrayList; import java.util.List; public class ListToArrayExample { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); int n = 3; // Number of elements to retrieve // Create a sublist containing the first 'n' elements List<Integer> subList = list.subList(0, Math.min(n, list.size())); // Convert the sublist to an array Integer[] resultArray = subList.toArray(new Integer[0]); // Print the elements in the array for (Integer num : resultArray) { System.out.print(num + " "); } } } 

In this example, we first create a List called list with some elements. We then specify the number of elements n that we want to retrieve from the beginning of the list.

Next, we use the list.subList(0, Math.min(n, list.size())) method to create a sublist containing the first n elements. The Math.min(n, list.size()) part ensures that we don't try to access more elements than the list contains.

Finally, we use the subList.toArray(new Integer[0]) method to convert the sublist to an array of Integer objects. The new Integer[0] argument is provided to specify the type of the resulting array.

The resultArray now contains the first n elements from the list, and you can work with it as needed.


More Tags

terraform benchmarking angular-gridster2 jpa-2.0 processstartinfo azure-active-directory android-asynctask sequelize.js task truststore

More Java Questions

More Other animals Calculators

More Animal pregnancy Calculators

More Internet Calculators

More Weather Calculators