我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
您可以尝试连接多个数组的方法:
public static <T> T[] concatMultipleArrays(T[]... arrays)
{
int length = 0;
for (T[] array : arrays)
{
length += array.length;
}
T[] result = (T[]) Array.newInstance(arrays.getClass().getComponentType(), length) ;
length = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, length, arrays[i].length);
length += arrays[i].length;
}
return result;
}
其他回答
ArrayList<String> both = new ArrayList(Arrays.asList(first));
both.addAll(Arrays.asList(second));
both.toArray(new String[0]);
应该会成功的。这是假设String[]第一个,String[]第二个
List<String> myList = new ArrayList<String>(Arrays.asList(first));
myList.addAll(new ArrayList<String>(Arrays.asList(second)));
String[] both = myList.toArray(new String[myList.size()]);
只是想添加,您也可以使用System.arraycopy:
import static java.lang.System.out;
import static java.lang.System.arraycopy;
import java.lang.reflect.Array;
class Playground {
@SuppressWarnings("unchecked")
public static <T>T[] combineArrays(T[] a1, T[] a2) {
T[] result = (T[]) Array.newInstance(a1.getClass().getComponentType(), a1.length+a2.length);
arraycopy(a1,0,result,0,a1.length);
arraycopy(a2,0,result,a1.length,a2.length);
return result;
}
public static void main(String[ ] args) {
String monthsString = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
String[] months = monthsString.split("(?<=\\G.{3})");
String daysString = "SUNMONTUEWEDTHUFRISAT";
String[] days = daysString.split("(?<=\\G.{3})");
for (String m : months) {
out.println(m);
}
out.println("===");
for (String d : days) {
out.println(d);
}
out.println("===");
String[] results = combineArrays(months, days);
for (String r : results) {
out.println(r);
}
out.println("===");
}
}
我使用下一个方法使用java8连接任意数量的相同类型的数组:
public static <G> G[] concatenate(IntFunction<G[]> generator, G[] ... arrays) {
int len = arrays.length;
if (len == 0) {
return generator.apply(0);
} else if (len == 1) {
return arrays[0];
}
int pos = 0;
Stream<G> result = Stream.concat(Arrays.stream(arrays[pos]), Arrays.stream(arrays[++pos]));
while (pos < len - 1) {
result = Stream.concat(result, Arrays.stream(arrays[++pos]));
}
return result.toArray(generator);
}
用法:
concatenate(String[]::new, new String[]{"one"}, new String[]{"two"}, new String[]{"three"})
or
concatenate(Integer[]::new, new Integer[]{1}, new Integer[]{2}, new Integer[]{3})
在Java 8中
public String[] concat(String[] arr1, String[] arr2){
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
Stream<String> stream = Stream.concat(stream1, stream2);
return Arrays.toString(stream.toArray(String[]::new));
}