简体   繁体   中英

arraylist<String> to array in java

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?

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);

怎么样:

String[] strarr = (String[])letter.toArray();

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()]); 

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]);

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM