我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
怎么样:
public String[] combineArray (String[] ... strings) {
List<String> tmpList = new ArrayList<String>();
for (int i = 0; i < strings.length; i++)
tmpList.addAll(Arrays.asList(strings[i]));
return tmpList.toArray(new String[tmpList.size()]);
}
其他回答
以下是对我有用的:
String[] data=null;
String[] data2=null;
ArrayList<String> data1 = new ArrayList<String>();
for(int i=0; i<2;i++) {
data2 = input.readLine().split(",");
data1.addAll(Arrays.asList(data2));
data= data1.toArray(new String[data1.size()]);
}
用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]
算法爱好者的另一个答案是:
public static String[] mergeArrays(String[] array1, String[] array2) {
int totalSize = array1.length + array2.length; // Get total size
String[] merged = new String[totalSize]; // Create new array
// Loop over the total size
for (int i = 0; i < totalSize; i++) {
if (i < array1.length) // If the current position is less than the length of the first array, take value from first array
merged[i] = array1[i]; // Position in first array is the current position
else // If current position is equal or greater than the first array, take value from second array.
merged[i] = array2[i - array1.length]; // Position in second array is current position minus length of first array.
}
return merged;
用法:
String[] array1str = new String[]{"a", "b", "c", "d"};
String[] array2str = new String[]{"e", "f", "g", "h", "i"};
String[] listTotalstr = mergeArrays(array1str, array2str);
System.out.println(Arrays.toString(listTotalstr));
结果:
[a, b, c, d, e, f, g, h, i]
简单一点怎么样
public static class Array {
public static <T> T[] concat(T[]... arrays) {
ArrayList<T> al = new ArrayList<T>();
for (T[] one : arrays)
Collections.addAll(al, one);
return (T[]) al.toArray(arrays[0].clone());
}
}
只需执行Array.concat(arr1,arr2)。只要arr1和arr2是相同类型的,这将为您提供另一个包含这两个数组的相同类型的数组。
非Java 8解决方案:
public static int[] combineArrays(int[] a, int[] b) {
int[] c = new int[a.length + b.length];
for (int i = 0; i < a.length; i++) {
c[i] = a[i];
}
for (int j = 0, k = a.length; j < b.length; j++, k++) {
c[k] = b[j];
}
return c;
}