By Chaitanya Singh | Filed Under: Java Conversion
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
- 1. Convert arraylist to array – List.toArray()
- 2. Convert arraylist to string array – Java 8 stream
- 3. Conclusion
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.
Output:
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 –
Given an ArrayList of String, the task is to convert the ArrayList to String array in java.
- Using ArrayList.get() Method
- Get the ArrayList of Strings.
- Find the size of ArrayList using size() method, and Create a String Array of this size.
- Fetch each element of the ArrayList one by one using get() method.
- Assigned each element into String Array using assignment(=) operator.
- Print String Array.
Below is the implementation of the above approach:
By Lokesh Gupta | Filed Under: Java ArrayList
Learn different ways to convert ArrayList to string array in Java with examples.
1. Convert arraylist to array – List.toArray()
This is most basic way to convert an arraylist containing string values to a string array.
2. Convert arraylist to string array – Java 8 stream
If you are using Java 8 or later, you can use stream and collector to get the string array from arraylist.
3. Conclusion
There are other ways also for this conversion from arraylist to string array using libraries such as apache commons and google guava, but those solutions add unnecessary complexity without adding any value. You can skip those solutions and stick to basics.
My preferred way is to use Java 8 streams. Feel free to share what’s your preferred way.
Источник: