×

Convert list to array Java

One of the popular collection interfaces for storing an ordered collection is the List. The List interface may contain repeating groups and preserves the insertion order of entries.

This article will describe the conversion techniques. The three basic techniques to turn a List into an array in Java are as follows:

  1. using List.get() function
  2. applying the toArray() function
  3. Streaming in Java 8

Using the get() Method

Streaming is one of the easiest approaches for converting a list into an array. This allows us to access each list element individually and add them to the array.

The get() method in the List interface has the following syntax:

public Ele get(int position)

The element that has been situated at the given position within the list is returned by the get() function.

To comprehend how to utilize the get() function of the list, let's look at an example of turning a list into such an array.

Example: ListToArrayEx1.java

//this program is for converting the list into an array
//import section
import java.io.*;  
import java.util.LinkedList;  
import java.util.List;  
// a class ListToArrayEx1 can be created for converting the given list into an array
public class ListToArrayEx1 {  
    // main() method of the program
    public static void main(String[] args)  
    {  
         // a linked list was created by declaring the objects to list 
         List<String> name = new LinkedList<String>();  
         // the method add() is used for adding the elements to the liked list 
         name.add("Ramu");  
         name.add("Sita");  
         name.add("Raghu");  
         name.add("Latha");  
         name.add("Mamatha");  
         // the size of the linked list is then stored in the length variable  
         int length = name.size();  
         // the array elements were stored like the string as the datatype  
         String[] nameArray = new String[ length ]; 
         //the loop is then iterated over each element over the list completes
         //and then con converted it to the list array 
         for (int i = 0; i < length; i++)  
             nameArray[i] = name.get(i);  
         // the values which are in the array are printed  
         System.out.println("Coverted the list to an array");  
         for (int j = 0; j < nameArray.length; j++) {  
             System.out.println((j+1)+" element in the array = "+nameArray[j]);  
         }  
    }   
}  

Output

Convert list to array Java

Applying the toArray() Method

The toArray() function makes it simple to change a list into an array. It is an additional approach to array creation from a list. All the entries in the list are returned in an array using the toArray() function. The elements in the resulting array are organized in the exact order as the list.

The List interface's toArray() method has had the corresponding format:

public <T> T[] toArray(T[] array)  

The toArray() function returns an array that contains every element in the list and either takes an array as a parameter or does not accept one.

To further comprehend how we may employ the list's toArray() method, let's see another example of transforming a list into such an array.

ListToArrayEx2.java

//this program is for converting the list into an array
//importing the required packages
import java.io.*;
import java.util.LinkedList;  
import java.util.List;  
//a class ListToArrayEx2 can be created for converting the given list into an array
public class ListToArrayEx2 {  
    // main() section of the program 
    public static void main(String[] args)  
    {  
         // a linked list was created by declaring the objects to list 
         List<String> name = new LinkedList<String>(); 
        // the add() method was used for pushing the elements to list 
         // use add() method of the list to add elements in the linked list  
         name.add("Panini");  
         name.add("Daniel");  
         name.add("Johny"); 
         name.add("Ramesh");  
         name.add("Mahesh");
         //the method toArray() method can be used for converting the list to an array
         String[] nameArray = name.toArray(new String[0]);  
         // the total elements in the list are printed  
         System.out.println("The list after converted to array");  
         for (int j = 0; j < nameArray.length; j++) {  
             System.out.println((j+1)+" element in array = "+nameArray[j]);  
         }  
    }   
}  

Output:

Convert list to array Java

Utilizing Stream

ma may also convert a List into an array utilizing the Stream feature included in Java 8.

The toArray() function of the List interface has the following syntax:

public <T> T[] toArray(T[] array) 

The toArray() function only takes one of two parameters: an array or nothing. All of the list's items are contained in the returned array.

ListToArrayExample3.java

//this program is for converting the list into an array
//importing the required packages
//import section
import java.io.*;  
import java.util.LinkedList;  
import java.util.List;  
//create  ListToArrayExample3 class
public class ListToArrayExample3 {  
    // main() section of the program 
    public static void main(String[] args)  
    {  
         // a linked list was created by declaring the objects to list   
         List<String> name = new LinkedList<String>();  
         // the add() method is used for adding elements to 
         name.add("Niranjan");  
         name.add("Somesh");  
         name.add("Johny");  
         name.add("Ramu");  
         name.add("Mamatha");  
         //the stream() method, which was used for converting the list to an array
         String[] nameArray = name.stream().toArray(String[] ::new);  
         // the result of all the elements in the array
         System.out.println("The converted list into an Array");  
         for (int j = 0; j < nameArray.length; j++) {  
             System.out.println((j+1)+" element in the array= "+nameArray[j]);  
         }  
    }   
}  

Output:

Convert list to array Java

Related Topics

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Best Practices to use String Class in Java

Use String Builder or String Buffer for String concatenation in place of + operator.Compare two strings by equals( ) method instead == operator.Call .equals( ) method on a known String...

3 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Java Create File

A File is a hypothetical way, which has no genuine presence. It is very much like while "using" that File that the major real activity of putting away something in...

5 minutes read.

Java Integer lowestOneBit()

The lowestOneBit () method of Java Integer class returns an int value with at most a single one-bit, in the position of the lowest-order one-bit in the specified int value.  Syntax public...

2 minutes read.

How to handle NullPointerException in Java

Introduction: Throwable class is the super or root class of the java exception hierarchy which contains two sub-classes. The classes’ are- ExceptionError Exception: If you are doing any wrong things in a...

3 minutes read.

Pig Latin Program in Java

Pig Latin Program in Java Pig Latin is a method for translating words of the English language into a different language. It is an encrypted word that is generated by using the following steps....

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

Difference Between replace() and replaceall() in Java

In this article, you will be acknowledged about the replace() and replaceall() methods in java. Also, most importantly you will be acknowledged the differences between them along with the example...

4 minutes read.

Java Boolean hashCode() Method

The hashCode() method of Boolean class returns the hash code for the specified Boolean object or the given Boolean value. Syntax public int hashCode()public int hashCode(boolean value) Parameters The parameter ‘value’ represents the value...

2 minutes read.

How to generate random numbers in Java

Random numbers, also known as fake numbers, are actually a part of a very large sequence, so they are called random numbers. In a defined set of numbers, every number...

6 minutes read.

Java Finally Keyword

The final block in Java is used to run essential code, such as connection closure, among other things. Whether an exception is resolved or not, the Java finally block has...

3 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Undo and Redo Operations in Java

Undo and redo operation are the most widely used operation while dealing with file. In this section, we will discuss how to implement undo and redo operation in Java. Undo Redo...

2 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

Convert milliseconds to date in Java

In Java, we frequently need to convert milliseconds into Dates with several formats, including dd MM yyyy and dd MM yyyy HH:mm:ss:SSS Z, among others. The Date class is one of the most...

4 minutes read.

Fork Join in Java

Multithreaded processors are being introduced in new computer systems today. The operation is faster due to multicore CPUs. Therefore, it becomes essential for a programmer to leverage multithreaded processors effectively...

4 minutes read.

Default Virtual Behaviour in C++ vs Java

Virtual Behaviour in C++: The class member methods in C++ are, by default, non-virtual. This implies that by simply defining it, they can be turned into virtual. The virtual class can be...

3 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Ganesha’s Pattern in Java

This part teaches us how to use stars and other special characters to write Ganesha's Pattern in Java programming. Among the most challenging Java pattern applications to code. The Ganesha will be...

3 minutes read.