1. Overview
In this ArrayList articles series, You'll be learning today how to convert a String into an ArrayList using java built-in methods. There are many scenarios in the real-time applications where we need to do transform the string into a list of objects. Typically string should be multiple values separated by a delimiter. For example take a String like "Started,Approved,In Progress,Completed". Here we are seeing the statues in string format and all these statuses are for processing the tickets raised by the users. This is the status flow. We need to now convert this string into a List<String>.
Note: String can have integers, double and strings values with a delimiter. The same below shown program works for any type of values present in the input string.
2. Write a program to convert String to ArrayList in Java
The below process and program are used to demonstrate to convert comma-separated values into ArrayList.
String allStatus = "Started,Approved,In Progress,Completed";
Notice that string has ',' delimiter which is separating each status. So, we can say comma as a delimiter here. String API has a method split() which takes a regex to match the pattern and split values. After successful split, split() method returns a string array String[]. This returned String[] array holds the values. Now, the last step is to convert this String array into a List using Arrays.asList() method. asList() is a static method so we can call directly with the class name.
package com.javaprogramto.engineering.programs; import java.util.Arrays; import java.util.List; /** * * Java Program To Convert String to ArrayList Using Arrays.asList() * * @author javaprogramto.com - Venkatesh * */ public class StringToArrayList { public static void main(String[] args) { String allStatus = "Started,Approved,In Progress,Completed"; System.out.println("string : " + allStatus); // spliting by comma String[] statusArray = allStatus.split(","); // converting string array to list ListstatusList = Arrays.asList(statusArray); // Iterating list of strings using for-each. System.out.println("Converted List values are : "); for (String status : statusList) { System.out.println(status); } } }
Output:
string : Started,Approved,In Progress,Completed Converted List values are : Started Approved In Progress Completed
Converted List<String> is printed using a for-each concept.
This can be done using Java 8 for each in a single line as below and will produce the same result. The order also preserved from String.
statusList.forEach(status -> System.out.println(status));
3. Conclusion
In this article, we've learned about how to convert comma-separated values into an ArrayList. The string can be having any delimiter such as #, *, !, | or @. For all of these delimiters should be passed to the split() method then next is to call Arrays.asList() method.
No comments:
Post a Comment
Please do not add any spam links in the comments section.