Harini
Harini

Reputation: 105

After spliting a string using stringspilt how will I store it in an arraylist?

I have a string variable similar to

           String my = "split it";

I split this using split().

           java.util.Arrays.toString(my.split("\\s+"))

The output is [split it]. But I want to store this in an arraylist, in FIRST index split and in SECOND index. Pls let me know how will I can achieve this.Thanks in advance.

Upvotes: 2

Views: 4559

Answers (4)

Suresh
Suresh

Reputation: 1504

String my ="String my";
String array[]= my.split(" ");
System.out.println(array[0]);
List<String > list=Arrays.asList(array);
System.out.println(list.get(0));

Upvotes: 0

Guillaume Polet
Guillaume Polet

Reputation: 47608

Arrays.asList(my.split("\\s+"))

Upvotes: 1

Marcelo
Marcelo

Reputation: 4608

String my = "split it";
String[] splitArray = my.split(" ");
List<String> splitList = new ArrayList<String>(Arrays.asList(splitArray));

Notice that calling new ArrayList... is needed if you want your List to be resizable, since Arrays.asList() will return a fixed-size list backed by the original array.

Upvotes: 1

Kris
Kris

Reputation: 5792

You can always use

new ArrayList(Arrays.asList(myArray));

assuming of course that myArray is a array from str.split(..)

or get an Iterable with Google Guava split method:

Iterable split = Splitter.on(",").split(stringToSplit);

of course you can replace a comman ',' with regex.

Upvotes: 2

Related Questions