Java ArrayList Conversions To Other Collections

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This Tutorial Discusses ArrayList Conversions to other Collections like Set, LinkedList, Lists, etc. along with Differences Between These Collections:

So far we have seen almost all the concepts related to ArrayList in Java. Apart from creating and manipulating ArrayList using various operations or methods provided by ArrayList class, sometimes it is also required to convert ArrayList to one or more collections.

=> Visit Here To Learn Java From Scratch.

Array list Conversion

In this tutorial, we will discuss some of the conversions from ArrayList to other collections that include List, LinkedList, Vector, Set, etc. We will also consider conversion between ArrayList and String. After conversions, we will also discuss the differences between ArrayLists and other Collections – Arrays, List, Vector, LinkedList, etc.

ArrayList To String Conversion

The following methods can be used to convert ArrayList to String.

#1) Using a StringBuilder object

import java.util.ArrayList;

public class Main {
   public static void main(String args[]) {
       //Create and initialize the ArrayList
      ArrayList<String> strList = new ArrayList<String>();
      strList.add("Software");
      strList.add("Testing");
      strList.add("Help");
      //print the ArrayList
      System.out.println("The ArrayList: " + strList);
      //define a stringbuilder object     
      StringBuffer sb = new StringBuffer();
      
      //append each ArrayList element to the stringbuilder object
      for (String str : strList) {
         sb.append(str + " ");
      }
      //convert stringbuilder to string and print it.
      String myStr = sb.toString();
      System.out.println("\nString from ArrayList: " + myStr);
   }
} 

Output:

The ArrayList: [Software, Testing, Help]
String from ArrayList: Software Testing Help

output

In the above program, a StringBuilder object is created. Then using the forEach loop, each element in the ArrayList is appended to the StringBuilder object. Then the StringBuilder object is converted to a string. Note that using the StringBuilder ‘append’ method; you can also append appropriate delimiter to the string.

In the above example, we have used space (“ “) as the delimiter.

#2) Using String.join () method

The method String.join () can be used to convert the ArrayList to String. Here, you can also pass appropriate delimiter to the join method.

The program below demonstrates this.

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        // create and initialize the ArrayList
        ArrayList<String> metroList = new ArrayList<>();
        metroList.add("Delhi");
        metroList.add("Mumbai");
        metroList.add("Chennai");
        metroList.add("Kolkata");
        //print the ArrayList
        System.out.println("The ArrayList: " + metroList);
        // Join with an empty delimiter to concat all strings.
        String resultStr = String.join(" ", metroList);
        System.out.println("\nString converted from ArrayList: "+resultStr);
    }
}

Output:

The ArrayList: [Delhi, Mumbai, Chennai, Kolkata]
String converted from ArrayList: Delhi Mumbai Chennai Kolkata

output

You can see that we directly pass the ArrayList as an argument to the String.join () method along with the delimiter.

For simple String ArrayLists, String.join () is the best method to convert to String. But for more complex ArrayLists objects, using StringBuilder is more efficient.

String To ArrayList Conversion

In order to convert a String to ArrayList, there are two steps:

  1. The string is split using the split () function and the substrings (split on appropriate delimiter) are stored in a string array.
  2. The string array obtained from splitting the string is then converted to ArrayList using ‘asList()’ method of the Arrays class.

The program to convert string to ArrayList is given below.

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
public class Main {
    public static void main(String args[]){
    //define a string
	String myStr = "The string to ArrayList program";
    //convert string to array using split function on spaces
	String strArray[] = myStr.split(" ");
	//print the string
	System.out.println("The input string : " + myStr);
    //declare an ArrayList
	List<String> strList = new ArrayList<String>();
	//convert string array to ArrayList using asList method
	strList = Arrays.asList(strArray);
    //print the resultant ArrayList
    System.out.println("\nThe ArrayList from String:" + strList );
   }
} 

Output:

The input string: The string to ArrayList program
The ArrayList from String:[The, string, to, ArrayList, program]

output

In the above program, we split the string into spaces and collect it in a string array. This array is then converted into an ArrayList of strings.

Convert list To ArrayList In Java

ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.

The program below shows the conversion of the list to ArrayList by adding all the list elements to the ArrayList.

import java.util.ArrayList;
import java.util.List;
 
public class Main {
    public static void main(String a[]){
        //create a list & initiliaze it
        List<String> collections_List = new ArrayList<String>();
        collections_List.add("ArrayList");
        collections_List.add("Vector");
        collections_List.add("LinkedList");
        collections_List.add("Stack");
        collections_List.add("Set");
        collections_List.add("Map");
        //print the list
        System.out.println("List contents: "+collections_List);
        //create an ArrayList        
        ArrayList<String> myList = new ArrayList<String>();
        //use addAll() method to add list elements to ArrayList
        myList.addAll(collections_List);
        //print the ArrayList
        System.out.println("\nArrayList after adding elements: "+myList);
    }
}

Output:

List contents: [ArrayList, Vector, LinkedList, Stack, Set, Map]
ArrayList after adding elements: [ArrayList, Vector, LinkedList, Stack, Set, Map]

output

Convert ArrayList To Set In Java

The following methods convert an ArrayList to a Set.

#1) Using a traditional iterative approach

This is the traditional approach. Here, we iterate through the list and add each element of the ArrayList to the set.

In the program below, we have an ArrayList of string. We declare a HashSet of string. Then using the forEach loop, we iterate over the ArrayList and add each element to the HashSet.

In a similar manner, we can also convert ArrayList to a treeSet.

import java.util.*; 
  
class Main { 
    public static void main(String[] args)  { 
          // Create & initialize an ArrayList
        ArrayList<String> colorsList = new ArrayList<String>
        (Arrays.asList("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow")); 
        //print the ArrayList
        System.out.println("The ArrayList:" + colorsList);
        //Declare a HashSet
        Set<String> hSet = new HashSet<String>(); 
        //Add each ArrayList element to the set
        for (String x : colorsList) 
            hSet.add(x); 
        //Print the HashSet  
        System.out.println("\nHashSet obtained from ArrayList: " + hSet); 
     } 
}

Output:

The ArrayList:[Red, Green, Blue, Cyan, Magenta, Yellow]
HashSet obtained from ArrayList: [Red, Cyan, Blue, Yellow, Magenta, Green]

output

#2) Using Set Constructor

The next method to convert an ArrayList to a set is using the constructor. In this method, we pass the ArrayList as an argument to the set constructor and thus initialize the set object with ArrayList elements.

The program below shows the use of ArrayList in creating a set object.

import java.util.*; 
  
class Main { 
    public static void main(String[] args)  { 
          // Create & initialize an ArrayList
        ArrayList<String> colorsList = new ArrayList<String>
        (Arrays.asList("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow")); 
        //print the ArrayList
        System.out.println("The ArrayList:" + colorsList);
        //Declare a TreeSet
       Set<String> tSet = new TreeSet<String>(colorsList); 
       //Print the TreeSet  
        System.out.println("\nTreeSet obtained from ArrayList: " + tSet); 
    } 
}

Output:

The ArrayList:[Red, Green, Blue, Cyan, Magenta, Yellow
TreeSet obtained from ArrayList: [Blue, Cyan, Green, Magenta, Red, Yellow]

output

#3) Using The addAll Method

You can also use the addAll method of Set to add all the elements of ArrayList to the set.

The following program uses the addAll method to add the elements of ArrayList to the HashSet.

import java.util.*; 
 
class Main { 
    public static void main(String[] args)  { 
        // Create & initialize an ArrayList
        ArrayList<String> colorsList = new ArrayList<String>
        (Arrays.asList("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow")); 
        //print the ArrayList
        System.out.println("The ArrayList:" + colorsList);
        //Declare a HashSet
        Set<String> hSet = new HashSet<String>(); 
        //use addAll method of HashSet to add elements of ArrayList
        hSet.addAll(colorsList);
        //Print the HashSet  
        System.out.println("\nHashSet obtained from ArrayList: " + hSet); 
     } 
}

Output:

The ArrayList:[Red, Green, Blue, Cyan, Magenta, Yellow]
HashSet obtained from ArrayList: [Red, Cyan, Blue, Yellow, Magenta, Green]

output

#4) Using Java 8 Stream

Streams are the new additions to Java 8. This stream class provides a method to convert ArrayList to stream and then to set.

The Java program below demonstrates the use of the stream class method to convert ArrayList to set.

import java.util.*; 
import java.util.stream.*; 
class Main { 
    public static void main(String[] args)  { 
        // Create & initialize an ArrayList
        ArrayList<String> colorsList = new ArrayList<String>
        (Arrays.asList("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow")); 
        //print the ArrayList
        System.out.println("The ArrayList:" + colorsList);
        
        // Convert ArrayList to set using stream 
        Set<String> set = colorsList.stream().collect(Collectors.toSet()); 
  
        //Print the Set  
        System.out.println("\nSet obtained from ArrayList: " + set); 
     } 
}

Output:

The ArrayList:[Red, Green, Blue, Cyan, Magenta, Yellow]
Set obtained from ArrayList: [Red, Cyan, Blue, Yellow, Magenta, Green]

output

Convert Set To ArrayList In Java

In the last section, we have seen the conversion of ArrayList to Set. The conversion from Set to ArrayList also uses the same methods as described above with the difference that the position of the set and ArrayList changes.

Given below are programming examples to convert Set to ArrayList. The other description for each method remains the same.

#1) Iterative Approach

import java.util.*; 
  
class Main { 
  public static void main(String[] args) { 
      // Create a set of strings & add elements to it 
    Set<String> set = new HashSet<String>(); 
    set.add("One"); 
    set.add("Two"); 
    set.add("Three"); 
    //print the set
    System.out.println("The given Set: " + set); 
    //create an ArrayList  
    ArrayList<String> numList = new ArrayList<String>(set.size()); 
    //add each set element to the ArrayList using add method
    for (String str : set) 
      numList.add(str); 
  
    //print the ArrayList
    System.out.println("\nArrayList obtained from Set: " + numList); 
  } 
}

Output:

The given Set: [One, Two, Three]
ArrayList obtained from Set: [One, Two, Three]

output

In the above program, we iterate through the Set and each set element is added to the ArrayList.

#2) Using Constructor

import java.util.*; 
  
class Main { 
  public static void main(String[] args) { 
    // Create a set of strings & add elements to it 
    Set<String> set = new HashSet<String>(); 
    set.add("One"); 
    set.add("Two"); 
    set.add("Three"); 
    //print the set
    System.out.println("The given Set: " + set); 
    //create an ArrayList and pass set to the constructor 
    List<String> numList = new ArrayList<String>(set); 
     //print the ArrayList
    System.out.println("\nArrayList obtained from Set: " + numList); 
  } 
}

Output:

The given Set: [One, Two, Three]
ArrayList obtained from Set: [One, Two, Three]

output

The above program creates a set and an ArrayList. The ArrayList object is created by providing a set object as an argument in its constructor.

#3) Using The addAll Method

import java.util.*; 
  
class Main { 
  public static void main(String[] args) {   
    // Create a set of strings & add elements to it 
    Set<String> set = new HashSet<String>(); 
    set.add("One"); 
    set.add("Two"); 
    set.add("Three"); 
    //print the set
    System.out.println("The given Set: " + set); 
    //create an ArrayList 
    List<String> numList = new ArrayList<String>(); 
    //use addAll method of ArrayList to add elements of set 
    numList.addAll(set); 
    //print the ArrayList
    System.out.println("\nArrayList obtained from Set: " + numList); 
  } 
}

Output:

The given Set: [One, Two, Three]
ArrayList obtained from Set: [One, Two, Three]

output

Here, we use the addAll method of ArrayList to add the elements from the set to the ArrayList.

#4) Using Java 8 Stream

import java.util.*; 
import java.util.stream.*; 
class Main { 
  public static void main(String[] args) { 
     // Create a set of strings & add elements to it 
    Set<String> set = new HashSet<String>(); 
    set.add("One"); 
    set.add("Two"); 
    set.add("Three"); 
    //print the set
    System.out.println("The given Set: " + set); 
    //create an ArrayList and using stream method,assign stream of elements to ArrayList
    List<String> numList = set.stream().collect(Collectors.toList()); 
  
    //print the ArrayList
    System.out.println("\nArrayList obtained from Set: " + numList); 
  } 
}

Output:

The given Set: [One, Two, Three]
ArrayList obtained from Set: [One, Two, Three]

output

The above program uses stream class to convert Set to ArrayList.

An Array Of ArrayList In Java

An Array of ArrayList as the name suggests consists of ArrayLists as its elements. Though the feature is not used regularly, it is used when efficient usage of memory space is a requirement.

The following program implements an Array of ArrayLists in Java.

import java.util.ArrayList;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		//define and initialize a num_list
		List<String> num_list = new ArrayList<>();
		num_list.add("One");
		num_list.add("Two");
		num_list.add("Two");
    		//define and initialize a colors_list
		List<String> colors_list = new ArrayList<>();
		colors_list.add("Red");
		colors_list.add("Green");
		colors_list.add("Blue");

        		//define Array of ArrayList with two elements
		List<String>[] arrayOfArrayList = new List[2];
		//add num_list as first element 
		arrayOfArrayList[0] = num_list;
		//add colors_list as second element
		arrayOfArrayList[1] = colors_list;
        		//print the contents of Array of ArrayList
        		System.out.println("Contents of Array of ArrayList:");
		for (int i = 0; i < arrayOfArrayList.length; i++) {
			List<String> list_str = arrayOfArrayList[i];
			System.out.println(list_str);
	}
}
}

Output:

Contents of Array of ArrayList:
[One, Two, Two]
[Red, Green, Blue]

output

In the above program, we first define two lists. Then we declare an Array of two ArrayList. Each element of this array is the ArrayList defined earlier. Finally, the contents of an Array of ArrayList is displayed using a for loop.

ArrayList Of Arrays In Java

Just as we have an Array of ArrayLists, we can also have ArrayList of Arrays. Here, each individual element of an ArrayList is an Array.

The below program demonstrates ArrayList of Arrays.

import java.util.*;

public class Main {
	public static void main(String[] args) {
		// declare ArrayList of String arrays
		ArrayList<String[]> ArrayList_Of_Arrays = new ArrayList<String[]>();
		//define individual string arrays
		String[] colors = { "Red", "Green", "Blue" };
		String[] cities = { "Pune", "Mumbai", "Delhi"};
		//add each array as element to ArrayList
		ArrayList_Of_Arrays.add(colors);
		ArrayList_Of_Arrays.add(cities);
		// print ArrayList of Arrays
		System.out.println("Contents of ArrayList of Arrays:");
		for (String[] strArr : ArrayList_Of_Arrays) {
			System.out.println(Arrays.toString(strArr));
		}
	}
}

Output:

Contents of ArrayList of Arrays:
[Red, Green, Blue]
[Pune, Mumbai, Delhi]

output

The above program demonstrates ArrayList of Arrays. Initially, we declare an ArrayList of String Arrays. This means each element of ArrayList will be a String Array. Next, we define two string Arrays. Then each of the Arrays is added to the ArrayList. Finally, we print the contents of ArrayList of Arrays.

To print the contents, we traverse the ArrayList using for loop. For each iteration, we print the contents of the ArrayList element which has an Array using Arrays.toString () method.

List Vs ArrayList In Java

The following tables show some of the differences between a List and ArrayList.

ListArrayList
The list is an interface in JavaArrayList is a part of the Java Collection framework
The list is implemented as an interfaceArrayList is implemented as a collection class
Extends Collection Interfaceimplements List interface & extends AbstractList
Part of System.Collection.generic namespacePart of System.Collections namespace
Using List, a list of elements can be created which can be accessed using indices.Using ArrayList, we can create a dynamic Array of elements or objects whose size automatically alters with the changes in contents.

Vector Vs ArrayList

Given below are some of the differences between a Vector and an ArrayList.

ArrayListLinkedList
ArrayList implements List interfaceLinkedList implements List and Deque interfaces.
Data storage and access are efficient in ArrayList.LinkedList is good at manipulating data.
ArrayList internally implements a dynamic array.LinkedList internally implements a doubly linked list.
Since ArrayList internally implements dynamic array, the addition/deletion of elements is slow as a lot of bit-shifting is required.LinkedList is faster as far as addition/removal of elements is concerned since no bit shifting is necessary.
Less memory overhead since in ArrayList only actual data is stored.More memory overhead since each node in LinkedList contains data as well as the address to the next node.

ArrayList vs LinkedList

Let us now discuss the various differences between an ArrayList and a LinkedList.

ArrayListLinkedList
ArrayList implements List interfaceLinkedList implements List and Deque interfaces.
Data storage and access are efficient in ArrayList.LinkedList is good at manipulating data.
ArrayList internally implements a dynamic array.LinkedList internally implements a doubly linked list.
Since ArrayList internally implements dynamic array, the addition/deletion of elements is slow as a lot of bit-shifting is required.LinkedList is faster as far as addition/removal of elements is concerned since no bit shifting is necessary.
Less memory overhead since in ArrayList only actual data is stored.More memory overhead since each node in LinkedList contains data as well as the address to the next node.

Frequently Asked Questions

Q #1) How do you convert an ArrayList to an Array in Java?

Answer: To convert an ArrayList to an Array in Java, one can use the toArray ( ) method from ArrayList API that converts a given ArrayList to an Array.

Q #2) How do you split a string and store it in an ArrayList in Java?

Answer: The string is split using a split () function. This method returns an Array of strings. Then using the Arrays.asList () method, the string array can be converted to an ArrayList of strings.

Q #3) What is the default size of an ArrayList?

Answer: An ArrayList object created without specifying the capacity has a size 0 as there are no elements added to the list. But the default capacity of this ArrayList is 10.

Q #4) What is the difference between length () and size () of ArrayList?

Answer: An ArrayList does not have a length () property or method. It provides only the size () method that returns the total number of elements in the ArrayList.

Q #5) What is the difference between the capacity and size of ArrayList?

Answer: ArrayList possesses both capacity and size. Capacity is the total size of the ArrayList or the total number of elements it can hold. Size is the number of elements or locations that have data in them.

For example, if ArrayList capacity is 10 and its size is 5, this means that an ArrayList can hold up to 10 elements, but at present only 5 locations have data in them.

Conclusion

In this tutorial, we discussed some of the additional concepts related to ArrayList like converting ArrayList to a string, list, set, and vice versa. We also discussed the differences between ArrayList and Vector, ArrayList and LinkedList, etc.

In our upcoming tutorial, we will take up another collection and learn it thoroughly.

=> Check Here To See A-Z Of Java Training Tutorials Here.

Was this helpful?

Thanks for your feedback!

Leave a Comment