Convert ArrayList of Object to ArrayList of String

In this java tutorial we are converting a String to an ArrayList. The steps for conversion are as follows:


1] First split the string using String split[] method and assign the substrings into an array of strings. We can split the string based on any character, expression etc.

2] Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays.asList[] method. This method returns a list created based on the elements of the specified array.

Program to convert String to ArrayList

In this java program we have a string which contains some numbers with delimiter as comma [,]. We are splitting the string based on the delimiter and then assigning those numbers to an array of strings.
Later we are copying all the elements of string array to an ArrayList using the asList[] method of Arrays.

import java.util.ArrayList; import java.util.List; import java.util.Arrays; public class JavaExample { public static void main[String args[]]{ String num = "22,33,44,55,66,77"; String str[] = num.split[","]; List al = new ArrayList[]; al = Arrays.asList[str]; for[String s: al]{ System.out.println[s]; } } }

Output:

22 33 44 55 66 77

Note: In the above example, the delimiter is comma however we can split the string based on any delimiter. For example if the string is hello hi namaste bye then we can split the string using whitespace as delimiter like this

Here we have provided whitespace as delimiter String str[] = num.split[" "];
PreviousNext

Video liên quan

Chủ Đề