Merge (or add) two arrays into one

From CodeCodex

Revision as of 02:07, 14 August 2010 by 211.2.129.92 (Talk)

Implementations

Java

The easy way is to convert the arrays into Lists, add one into another and finally convert back to an array. <highlightsyntax language="java122"> import java.util.*;

public class Test2 {

   public static void main(String args[]){
     String a[] = {"a", "b", "c"};
     String b[] = {"d", "e" };
     
     List<String> list = new ArrayList<String>(Arrays.asList(a));
     list.addAll(Arrays.asList(b));
     
     Object [] c = list.toArray();
     
     System.out.println(Arrays.toString(c));
     /*
     output :  [a, b, c, d, e]
     */ 
   }
 }

</highlightsyntax> From there a more versatile method is developped to accept a list of arrays to be merged into one. <highlightsyntax language="java122">

import java.util.*;

public class CollectionUtils {

 @SuppressWarnings("unchecked")
 public static <T> T[] join(T[] ... arrays) {
   // calculate size of target array
   int size = 0;
   for (T[] array : arrays) {
     size += array.length;
   }
   // create list of appropriate size
   List<T> list = new ArrayList<T>(size);
   for (T[] array : arrays) {
     list.addAll(Arrays.asList(array));
   }
   // need to the @suppresswarning() here
   T[] array = (T[]) list.toArray();
   return array;
 }


 public static void main(String[] args) {

   String a[] = { "1", "2", "3" };
   String b[] = { "4", "5", "6" };
   String c[] = { "7", "8", "9" };
   
   System.out.println(java.util.Arrays.toString((join(a,b,c))));
   /*
    * output : 
    *    [1, 2, 3, 4, 5, 6, 7, 8, 9]
    */
 }

} </highlightsyntax>

Ruby

a = [1, 2, 3, 4]
b = [2, 4, 6, 8]
p a + b         #=> [1, 2, 3, 4, 2, 4, 6, 8]
p a | b         #=> [1, 2, 3, 4, 6, 8]

a.concat(b)
p a             #=> [1, 2, 3, 4, 2, 4, 6, 8]