Good day!

I need to combine two arrays of string type, in what simple way can I do this?

String[] bothArray(String[] first, String[] second) { return ??; } 

    3 answers 3

    If you are allowed to use Java8 , you can use the Stream class and lambdas:

     import java.util.Arrays; import java.util.stream.Stream; // . . . String[] bothArray(final String[] first, final String[] second) { return Stream.concat(Stream.of(first), Stream.of(second)).toArray(String[]::new); } 

    Compact, beautiful and does not require external components.

    • As for me, this is the best way. Thanks for the answer - dirkgntly

    Using the Apache Commons library:

     String[] both = (String[])ArrayUtils.addAll(first, second); 

    from here


    Another variant

     public static String[] combine(String[] a, String[] b){ int length = a.length + b.length; String[] result = new String[length]; System.arraycopy(a, 0, result, 0, a.length); System.arraycopy(b, 0, result, a.length, b.length); return result; } 

    source with examples


    Another option for all types. Here you can use not only primitive types, but also objects

     public <T> T[] concatenate (T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen+bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } 

    a source

    • @LEQADA thanks hurry - Saidolim

    And one more option. (Rarely see his mention)

     String[] array; StringBuilder newStr = new StringBuilder(); for(String data: array){ newStr.append(data); } return newStr.toString(); 
    • one
      Good old StringBuilder. - Nick Volynkin
    • Yes, the concat is not comparable with StringBuilder. (I rarely see him mentioned?) It’s like, in this article, yes. - Denis Kotlyarov