Java ArrayList: creating an ArrayList from splitting of a string on multiple delimiters

Overview

A common task in various programming languages is to split a string based on delimiter and create a resulting array. In java we sometimes prefer to utilize collections instead of a basic array object, luckily java has the Arrays object that can be used to perform various functions on an inputted array.

The Step by Step

In java the String object has a built in split function that takes a regular expression as an input and returns an array of string values split by the regex. lets illustrate this by creating a new String.

String str = new String("001,002,003,004;005:006");

Next lets split the string based on 3 delimiters ; , and |

String[] sArray = str.split( "[,;:]" );

This will return a String array containing the values 001, 002, 003, 004, 005, and 006 as the regex [,;:] means to match any character contained between the []. Once we have our String Array we can then utilize the Arrays Class’s asList static function to convert the Array to a list to instantiate an ArrayList

List sList = new ArrayList( Arrays.asList(sArray) );

If we wanted to condense the above to one line we could use the following:

List sList = new ArrayList( Arrays.asList( str.split( "[,:;]" ) );

Conclusion

That is the process in a nut shell, don’t forget that with user supplied information you may also want to scrub your data for any invalid values or for empty values especially when your delimiter is a new line.  To do this you can easily use an Iterator or manipulate the array generated by the split function before generating the Array List.

// Java //

Comments & Questions

Add Your Comment