0

How do I concatenate, or append, all of the arrays that contain text strings into a single array? From the following code:

    String nList[] = {"indonesia", "thailand", "australia"};

    int nIndex[] = {100, 220, 100};

    String vkList[] = {"wounded", "hurt"};

    int vkIndex[] = {309, 430, 550};

    String skList[] = {"robbed", "detained"};

    int skIndex[] = {120, 225};

    String nationality = "";

    //System.out.println(nationality);

I want to store all strings of all three string-containing arrays:

    String nList[] = {"indonesia", "thailand", "australia"};

    String vkList[] = {"wounded", "hurt"};

    String skList[] = {"robbed", "detained"};

into a single array, say array1[].

modarwish
  • 72
  • 1
  • 8

3 Answers3

0
ArrayList<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));

String[] result = (String[])temp.toArray();
Zong
  • 6,160
  • 5
  • 32
  • 46
0

You can add the content of each array to a temporary List and then convert it's content to a String[].

List<String> temp = new ArrayList<String>();
temp.addAll(Arrays.asList(nList));
temp.addAll(Arrays.asList(vkList));
temp.addAll(Arrays.asList(skList));

String[] result = new String[temp.size()];
for (int i = 0; i < temp.size(); i++) {
    result[i] = (String) temp.get(i);
}

Alternatively, you can use Guava's ObjectArrays#concat(T[] first, T[] second, Class< T > type) method, which returns a new array that contains the concatenated contents of two given arrays. For example:

String[] concatTwoArrays = ObjectArrays.concat(nList, vkList, String.class);
String[] concatTheThirdArray = ObjectArrays.concat(concatTwoArrays, skList, String.class);
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
0
public static String[] join(String [] ... parms) {
 // calculate size of target array
 int size = 0;
 for (String[] array : parms) {
   size += array.length;
 }

 String[] result = new String[size];

 int j = 0;
 for (String[] array : parms) {
   for (String s : array) {
     result[j++] = s;
   }
 }
return result;
}

Just define your own join method. Found @ http://www.rgagnon.com/javadetails/java-0636.html

Ben
  • 1,157
  • 6
  • 11