List to Array Java

Sometimes, in every programming language, it is required to convert DS elements into a string array. This can be done in Java very easily (it is time to prove that Java is simple to practice). Let is see an example on List to Array.

In the following code, an Integer list is converted into String list and also into a String array.

List accepts null values also. For more code manipulation, null is added to Integer list purposefully. Two String lists are generated with the elements of Integer list – one string list accepting null value and the another without accepting null value.

Observe the code on List to Array.
import java.util.*;
public class Demo
{
  public static void main(String args[]) throws Exception
  {     		                     // creating a List with Integer elements
    List numList = new ArrayList();
    numList.add(10);
    numList.add(20);
    numList.add(null);                       // observe, List is added with null value also
    numList.add(30);
                                             // converting Integer list into String list where null value of Integer list is added to String list
    // List stringList = new ArrayList();  avoid this as it requires many times the array list resizing   
    List stringList = new ArrayList(numList.size());           
                                            // at a time the array list object is created with required size
   
    for (Integer tempInt : numList) 
    { 
      stringList.add(String.valueOf(tempInt)); 
    }
    System.out.println("Elements of Integer List (numList): "+ numList);
    System.out.println("Elements of String List WITH null addition (stringList): "+ stringList);

                            // converting Integer list into String list where null value of Integer list is NOT added to String list
    List stringList1 = new ArrayList(numList.size());
    for (Integer tempInt : numList) 
    { 
      if(!(tempInt == null))                // not to accept null values
        stringList1.add(String.valueOf(tempInt)); 
    }
    System.out.println("Elements of String List WITHOUT null addition (stringList1): "+ stringList1);
                                                			    
                                           // converting String list to String array
    String stringArray[] = stringList.toArray(new String[stringList.size()]);
    System.out.println("Elements of string array: " + Arrays.toString(stringArray));
  }
}

List to Array Java

A generics list numList that stores only Integers is created and added with a null value also.

A string list, stringList is created with the size of integer list, numList.

String.valueOf() converts any data type and object into string form.
toArray() method of Arrays class is used to convert string list into string array.
toString() is used to print array elements of stringArray.

View All for Java Differences on 90 Topics

Leave a Comment

Your email address will not be published.