Java String split() Method
In this post we will learn how we can convert a comma-separated String
into the arrayList
in Java. The split()
method that splits the String into array of sub-string based on the given delimiter or regular expression.
Syntax
str.split(regex, limit);
Parameter
- regex – Regular expression or Delimiter(common(,) and space are mostly used) to split the string to array
- limit – number of elements in the returned array. However when the limit is zero then the returned array would be having all the substrings excluding the trailing empty Strings.
Throws
if the syntax of specified regular expression or a delimiter is not valid.
Example
In this below code, we split the String by comma(,) to array of String. Use Arrays.asList
to convert the java.util.Arrays
to java.util.ArrayList
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SplitJavaMethod { public static void main(String[] args) { String str = "Parker, Harry, Jim, Gamma, Sigma"; // To array String[] arr = str.split(","); System.out.println("string Array : " + Arrays.toString(arr)); List<String> l = Arrays.asList(str.split(",")); System.out.println("Fixed-size List: " + l); List<String> l2 = new ArrayList<>(Arrays.asList(str.split(","))); System.out.println("To ArrayList : " + l2); } }
Output
string Array : [Parker, Harry, Jim, Gamma, Sigma] Fixed-size List: [Parker, Harry, Jim, Gamma, Sigma] To ArrayList : [Parker, Harry, Jim, Gamma, Sigma]
Passing the limit parameter
String str = "Hai! Welocome Poopcode Reader."; // To array System.out.println("String Array with limit : " + Arrays.toString(str.split(" ", 2))); System.out.println("String Array without limit: " + Arrays.toString(str.split(" "))); //Output //String Array with limit : [Hai!, Welocome Poopcode Reader.] //String Array without limit: [Hai!, Welocome, Poopcode, Reader.]
In the above code snippet, i have passed the limit 2 into the split() method it result with the array length of 2.
Hope this post is useful and understandable 🙂