user3407944
user3407944

Reputation:

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?

Upvotes: 4

Views: 32252

Answers (3)

Satya Pendem
Satya Pendem

Reputation: 325

We can split like below.

List<String> valueSplitList = Arrays.asList(myString.split(","));

Upvotes: 0

ced-b
ced-b

Reputation: 4065

There is no such thing as a Split functionfor list, but you can do the split and then convert to a List

List myList = Arrays.asList(myString.split(","));

Upvotes: 0

Boann
Boann

Reputation: 50061

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(","));

Upvotes: 7

Related Questions