Reputation: 299
i have this list if an arrayList:
[a b c d,e f g h, i j k l]
and i want to separate them to an array become:
temp_array[0]=a
temp_array[1]=b
temp_array[2]=c
temp_array[3]=d
i have done by using multidimensional array(2d array) and using split() method like this:
static ArrayList<String> letter = new ArrayList<String>();
temp_array = new String[letter.size()][];
for(int i=0; i<letter.size();i++)
{
String temp = output_list.get(i);
temp_array[i] = temp.split(" ");
}
but, i have the problem using double array and i want to use just an array like temp_array[].anyone can help me?
Upvotes: 0
Views: 585
Reputation: 425033
Here's a one-line solution. Because you know they are all letters, you can just do this:
List<String> input = Arrays.asList("a b c d", "e f g h", "i j k l");
System.out.println(input);
// Here's the one line:
String[] letters = input.toString().replaceAll("(\\[|\\])", "").split("\\b\\W+\\b");
System.out.println(Arrays.toString(letters));
Output:
[a b c d, e f g h, i j k l]
[a, b, c, d, e, f, g, h, i, j, k, l]
Upvotes: 0
Reputation: 217
Try this one,
ArrayList<String> a=new ArrayList<String>();
a.add("a");a.add("b");a.add("c");a.add("d");a.add("e");
a.add("j");a.add("i");a.add("h");a.add("g");a.add("f");
String [] countries = a.toArray(new String[a.size()]);
for(int i=0;i<a.size();i++){
countries[i]=a.get(i);
}
for(int j=0;j<countries.length;j++)
System.out.println("countries["+j+"]= "+countries[j]);
Upvotes: 0
Reputation:
It sounds like you need to use a temporary list to store it in. Also, is this question homework?
static ArrayList<String> letter = new ArrayList<String>(); // Your input
ArrayList<String> output = new ArrayList<String>();
for(String str : letter) {
String[] tmp = str.split("\\s"); // Whitespace regex
for(String s : tmp) {
output.add(s); // Put the letter into the list
}
}
// Convert to an array
String[] finalArray = output.toArray(new String[output.size()]);
Upvotes: 0
Reputation: 5086
ArrayList<T>
has a toArray(T[])
method which you can use like this to obtain the array you want:
String[] temp_array = new String[letter.size()];
letter.toArray(temp_array);
Upvotes: 2