Merge (or add) two arrays into one

From CodeCodex

Implementations[edit]

Erlang[edit]

-module(codex).
-export([merge_tuple/1, merge_tuple/2]).

merge_tuple(A, B) ->
    list_to_tuple( tuple_to_list(A) ++ tuple_to_list(B) ).

merge_tuple(ListOfTuple) ->
    F = fun(X, Acc) -> Acc ++ tuple_to_list(X) end,
    list_to_tuple( lists:foldl(F, [], ListOfTuple) ).

The use example (Eshell)

1> codex:merge_tuple({1,2,3},{a,b,c}).
{1,2,3,a,b,c}
2> codex:merge_tuple([{1,2,3},{a,b,c},{4,5}]).    
{1,2,3,a,b,c,4,5}

Java[edit]

The easy way is to convert the arrays into Lists, add one into another and finally convert back to an array.

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]
      */ 
    }
  }

From there a more versatile method is developped to accept a list of arrays to be merged into one.

 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]
     */
  }
}

Ruby[edit]

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]

Tcl[edit]

set l {a b c}
set m {d e}
set n [concat $l $m]