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 ??; }
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.
Using the Apache Commons library:
String[] both = (String[])ArrayUtils.addAll(first, second);
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; }
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; }
And one more option. (Rarely see his mention)
String[] array; StringBuilder newStr = new StringBuilder(); for(String data: array){ newStr.append(data); } return newStr.toString();
Source: https://ru.stackoverflow.com/questions/478394/
All Articles