×

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 Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Java Keywords

Java Keywords The particular words which are used in java programming language that act like a key or important words to write a code are called java keywords. Java Keywords are...

4 minutes read.

Java vs Golang

Java Java is both a programming language and a platform. Java is a high-level, dependable, object-oriented, and secure programming language. Java was developed in 1995 by Sun Microsystems, which is now an...

4 minutes read.

How to Compare Two Strings in Java

How to Compare Two Strings in Java On the basis of reference or content, one can compare two strings in Java. String comparison is used in reference matching (== operator), sorting...

4 minutes read.

Cast Operator in Java

A cast is a unique operator that completely converts one type of data into another. Casts are unary operators and have the same priority as other unary operators. Type casting in...

3 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Method Overloading In Java

If the same class consists of different methods with the same name and the methods can vary by different number of parameters then it is known as Method Overloading. Method...

2 minutes read.

Java Array Generic

Creating Generic Array in Java A collection of comparable sorts of data is kept in an array. In Java, making a generic array is challenging. The type information of an array's...

4 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Java Single Linkedlist

Like arrays, linked lists are a type of linear data structure. Unlike arrays, which store each element in the same location, linked lists employ pointers to connect the elements together. In...

25 minutes read.

Gregorian Calendar Java Current Date

GregorianCalendar class uses the Gregorian and Julian calendars. Dates are calculated by projecting present laws forever backward and forward in time. As a consequence, GregorianCalendar may be utilised to create...

8 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

String Declaration in Java

A string is a group of characters. In Java, the string can be treated as both class and datatype. In Java programming, the String class have many advantages. Everything in...

3 minutes read.

Java OCR

In this article, you will be acknowledged about what is a tesseract OCR, how it works, what are its used and advantages and disadvantages. Also, you will be able to...

4 minutes read.