logo

Перетворення списку на масив у Java

The Список це один із широко використовуваних інтерфейсів колекції, який використовується для зберігання впорядкованої колекції. Інтерфейс списку підтримує порядок вставлення елементів і також може зберігати повторювані значення.

У цьому розділі ми зрозуміємо, як можна перетворити список на масив. У Java ми в основному маємо три способи перетворити список на масив, які є такими:

  1. Використання методу get() списку
  2. Використання методу toArray().
  3. Використання Stream у Java 8

Використання методу get().

Це один із найпростіших способів перетворити список на масив. Таким чином ми отримуємо доступ до всіх елементів списку один за іншим і додаємо їх у масив.

математичні методи в java

Синтаксис отримати() Метод інтерфейсу списку виглядає наступним чином:

 public Ele get(int pos) 

Метод get() повертає елемент, який розташований у вказаній позиції у списку.

Давайте розглянемо приклад перетворення списку в масив, щоб зрозуміти, як ми можемо використовувати отримати() метод списку.

ConvertListToArrayExample1.java

 import java.io.*; import java.util.LinkedList; import java.util.List; // create ConvertListToArrayExample1 class to convert a list into an array class ConvertListToArrayExample1 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // get size of list and store it into len variable int len = names.size(); // declare and initialize array of type string to store list elements String[] namesArray = new String[ len ]; // iterate list using for loop and add all the elements into namesArray one by one to convert names list into an array for (int i = 0; i <len; i++) namesarray[i]="names.get(i);" print all the elements of array system.out.println('after converting list into an array'); for (int j="0;" < namesarray.length; j++) { system.out.println((j+1)+' element is '+namesarray[j]); } pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java.webp" alt="Convert List to Array in Java"> <h2>Using toArray() Method</h2> <p>It is another way of converting a list into an array. By using the toArray() method, we can easily convert a list into an array. The toArray() method returns an array having all the elements in the list. The returned array contains elements in the same sequence as the list.</p> <p>The syntax of the <strong>toArray()</strong> method of the List interface is as follows:</p> <pre> public T[] toArray(T[] a) </pre> <p>The toArray() method either accepts an array as a parameter or no parameter, and it returns an array containing all the elements in the list.</p> <p>Let&apos;s take another example of converting a list into an array to understand how we can use the <strong>toArray()</strong> method of the list.</p> <p> <strong>ConvertListToArrayExample2.java</strong> </p> <pre> import java.io.*; import java.util.LinkedList; import java.util.List; //create ConvertListToArrayExample2 class to convert a list into an array class ConvertListToArrayExample2 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // use toArray() method to convert a list into an array String[] namesArray = names.toArray(new String[0]); // print all the elements of the array System.out.println(&apos;After converting List into an Array&apos;); for (int j = 0; j <namesarray.length; j++) { system.out.println((j+1)+' element of the array is '+namesarray[j]); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java-2.webp" alt="Convert List to Array in Java"> <h2>Using Stream</h2> <p>There is one more way of converting a List into an array, i.e., by using Stream introduced in Java8.</p> <p>The syntax of the <strong>toArray()</strong> method of the List interface is as follows:</p> <pre> public T[] toArray(T[] a) </pre> <p>The toArray() method either accepts an array as a parameter or no parameter. It returns an array containing all the elements in the list.</p> <p>Let&apos;s take another example of converting a list into an array to understand how we can use the <strong>toArray()</strong> method of the list.</p> <p> <strong>ConvertListToArrayExample3.java</strong> </p> <pre> import java.io.*; import java.util.LinkedList; import java.util.List; //create ConvertListToArrayExample3 class to convert a list into an array class ConvertListToArrayExample3 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // use stream() method to convert a list into an array String[] namesArray = names.stream().toArray(String[] ::new); // print all the elements of the array System.out.println(&apos;After converting List into an Array&apos;); for (int j = 0; j <namesarray.length; j++) { system.out.println((j+1)+' element of the array is '+namesarray[j]); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java-3.webp" alt="Convert List to Array in Java"> <p>In Java, we mostly use get() and toArray() methods for converting a list into an array. The stream() method is not efficient in comparison of get() and toArray() methods.</p> <hr></namesarray.length;></pre></namesarray.length;></pre></len;>

Метод toArray() або приймає масив як параметр, або не приймає параметр, і повертає масив, що містить усі елементи списку.

Давайте розглянемо інший приклад перетворення списку в масив, щоб зрозуміти, як ми можемо використовувати toArray() метод списку.

ConvertListToArrayExample2.java

 import java.io.*; import java.util.LinkedList; import java.util.List; //create ConvertListToArrayExample2 class to convert a list into an array class ConvertListToArrayExample2 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // use toArray() method to convert a list into an array String[] namesArray = names.toArray(new String[0]); // print all the elements of the array System.out.println(&apos;After converting List into an Array&apos;); for (int j = 0; j <namesarray.length; j++) { system.out.println((j+1)+\' element of the array is \'+namesarray[j]); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java-2.webp" alt="Convert List to Array in Java"> <h2>Using Stream</h2> <p>There is one more way of converting a List into an array, i.e., by using Stream introduced in Java8.</p> <p>The syntax of the <strong>toArray()</strong> method of the List interface is as follows:</p> <pre> public T[] toArray(T[] a) </pre> <p>The toArray() method either accepts an array as a parameter or no parameter. It returns an array containing all the elements in the list.</p> <p>Let&apos;s take another example of converting a list into an array to understand how we can use the <strong>toArray()</strong> method of the list.</p> <p> <strong>ConvertListToArrayExample3.java</strong> </p> <pre> import java.io.*; import java.util.LinkedList; import java.util.List; //create ConvertListToArrayExample3 class to convert a list into an array class ConvertListToArrayExample3 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // use stream() method to convert a list into an array String[] namesArray = names.stream().toArray(String[] ::new); // print all the elements of the array System.out.println(&apos;After converting List into an Array&apos;); for (int j = 0; j <namesarray.length; j++) { system.out.println((j+1)+\' element of the array is \'+namesarray[j]); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java-3.webp" alt="Convert List to Array in Java"> <p>In Java, we mostly use get() and toArray() methods for converting a list into an array. The stream() method is not efficient in comparison of get() and toArray() methods.</p> <hr></namesarray.length;></pre></namesarray.length;>

Метод toArray() або приймає масив як параметр, або не приймає параметр. Він повертає масив, що містить усі елементи списку.

Давайте розглянемо інший приклад перетворення списку в масив, щоб зрозуміти, як ми можемо використовувати toArray() метод списку.

ConvertListToArrayExample3.java

 import java.io.*; import java.util.LinkedList; import java.util.List; //create ConvertListToArrayExample3 class to convert a list into an array class ConvertListToArrayExample3 { // main() method start public static void main(String[] args) { // create linked list by declaring an object of List List names = new LinkedList(); // use add() method of the list to add elements in the linked list names.add(&apos;Paul&apos;); names.add(&apos;Donal&apos;); names.add(&apos;James&apos;); names.add(&apos;Robert&apos;); names.add(&apos;Mery&apos;); // use stream() method to convert a list into an array String[] namesArray = names.stream().toArray(String[] ::new); // print all the elements of the array System.out.println(&apos;After converting List into an Array&apos;); for (int j = 0; j <namesarray.length; j++) { system.out.println((j+1)+\' element of the array is \'+namesarray[j]); } < pre> <p> <strong>Output:</strong> </p> <img src="//techcodeview.com/img/java-tutorial/59/convert-list-array-java-3.webp" alt="Convert List to Array in Java"> <p>In Java, we mostly use get() and toArray() methods for converting a list into an array. The stream() method is not efficient in comparison of get() and toArray() methods.</p> <hr></namesarray.length;>