我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
这里是silvertab解决方案的一个修改,对泛型进行了改进:
static <T> T[] concat(T[] a, T[] b) {
final int alen = a.length;
final int blen = b.length;
final T[] result = (T[]) java.lang.reflect.Array.
newInstance(a.getClass().getComponentType(), alen + blen);
System.arraycopy(a, 0, result, 0, alen);
System.arraycopy(b, 0, result, alen, blen);
return result;
}
注意:请参阅Joachim的Java 6解决方案答案。它不仅消除了警告;它也更短,更高效,更容易阅读!
其他回答
使用流的Java8的另一种方式
public String[] concatString(String[] a, String[] b){
Stream<String> streamA = Arrays.stream(a);
Stream<String> streamB = Arrays.stream(b);
return Stream.concat(streamA, streamB).toArray(String[]::new);
}
Object[] mixArray(String[] a, String[] b)
String[] s1 = a;
String[] s2 = b;
Object[] result;
List<String> input = new ArrayList<String>();
for (int i = 0; i < s1.length; i++)
{
input.add(s1[i]);
}
for (int i = 0; i < s2.length; i++)
{
input.add(s2[i]);
}
result = input.toArray();
return result;
我测试了以下代码,工作正常
我还使用了library:org.apache.mons.lang.ArrayUtils
public void testConcatArrayString(){
String[] a = null;
String[] b = null;
String[] c = null;
a = new String[] {"1","2","3","4","5"};
b = new String[] {"A","B","C","D","E"};
c = (String[]) ArrayUtils.addAll(a, b);
if(c!=null){
for(int i=0; i<c.length; i++){
System.out.println("c[" + (i+1) + "] = " + c[i]);
}
}
}
当做
/**
* With Java Streams
* @param first First Array
* @param second Second Array
* @return Merged Array
*/
String[] mergeArrayOfStrings(String[] first, String[] second) {
return Stream.concat(Arrays.stream(first), Arrays.stream(second)).toArray(String[]::new);
}
用lambda连接一系列紧凑、快速且类型安全的数组
@SafeVarargs
public static <T> T[] concat( T[]... arrays ) {
return( Stream.of( arrays ).reduce( ( arr1, arr2 ) -> {
T[] rslt = Arrays.copyOf( arr1, arr1.length + arr2.length );
System.arraycopy( arr2, 0, rslt, arr1.length, arr2.length );
return( rslt );
} ).orElse( null ) );
};
在没有参数的情况下调用时返回null
例如,具有3个阵列:
String[] a = new String[] { "a", "b", "c", "d" };
String[] b = new String[] { "e", "f", "g", "h" };
String[] c = new String[] { "i", "j", "k", "l" };
concat( a, b, c ); // [a, b, c, d, e, f, g, h, i, j, k, l]
“……可能是唯一通用和类型安全的方法”–适用于:
Number[] array1 = { 1, 2, 3 };
Number[] array2 = { 4.0, 5.0, 6.0 };
Number[] array = concat( array1, array2 ); // [1, 2, 3, 4.0, 5.0, 6.0]