Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

Java String to ArrayList

This Java example shows how to convert Java String to ArrayList object.
  1. import java.util.ArrayList;
  2.  
  3. //Java String to ArrayList
  4.  
  5. public class StringToArrayList {
  6.  
  7.     public static void main(String args[]){
  8.        
  9.         //original string containing numbers
  10.         String strNumbers = "One Two Three Four Five";
  11.        
  12.         //split the string using split method of String class
  13.         String[] numbers = strNumbers.split(" ");
  14.        
  15.         //create new ArrayList object
  16.         ArrayList<String> aListNumbers = new ArrayList<String>();
  17.        
  18.         //add individual numbers to the ArrayLists
  19.         for(int i=0; i< numbers.length; i++){
  20.             aListNumbers.add(numbers[i]);
  21.         }
  22.        
  23.         System.out.println("String converted to ArrayList: " + aListNumbers);
  24.     }
  25. }
  26.  
  27. /*
  28. Output of the above given Java String to ArrayList example would be
  29. String converted to ArrayList: [One, Two, Three, Four, Five]
  30.  */
Your rating: None Average: 3 (3 votes)
Share this

Post new comment

6 + 13 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.