Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a String to an ArrayList?

I know there is a String split method that returns an array but I need an ArrayList.

I am getting input from a textfield (a list of numbers; e.g. 2,6,9,5) and then splitting it at each comma:

String str = numbersTextField.getText();
String[] strParts = str.split(",");

Is there a way to do this with an ArrayList instead of an array?


1 Answers

You can create an ArrayList from the array via Arrays.asList:

ArrayList<String> parts = new ArrayList<>(
    Arrays.asList(textField.getText().split(",")));

If you don't need it to specifically be an ArrayList, and can use any type of List, you can use the result of Arrays.asList directly (which will be a fixed-size list):

List<String> parts = Arrays.asList(textField.getText().split(","));
like image 132
Boann Avatar answered Oct 30 '25 13:10

Boann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!