我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
使用Java集合
好吧,Java没有提供连接数组的助手方法。然而,自Java5以来,Collections实用程序类引入了addAll(Collection<?super T>c,T…elements)方法。
我们可以创建一个List对象,然后调用该方法两次,将这两个数组添加到列表中。最后,我们将生成的List转换回数组:
static <T> T[] concatWithCollection(T[] array1, T[] array2) {
List<T> resultList = new ArrayList<>(array1.length + array2.length);
Collections.addAll(resultList, array1);
Collections.addAll(resultList, array2);
@SuppressWarnings("unchecked")
//the type cast is safe as the array1 has the type T[]
T[] resultArray = (T[]) Array.newInstance(array1.getClass().getComponentType(), 0);
return resultList.toArray(resultArray);
}
Test
@Test
public void givenTwoStringArrays_whenConcatWithList_thenGetExpectedResult() {
String[] result = ArrayConcatUtil.concatWithCollection(strArray1, strArray2);
assertThat(result).isEqualTo(expectedStringArray);
}
其他回答
使用流的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);
}
FunctionalJava库有一个数组包装器类,它为数组提供了方便的方法,如串联。
import static fj.data.Array.array;
…然后
Array<String> both = array(first).append(array(second));
要取回展开的数组,请调用
String[] s = both.array();
在Haskell中,您可以执行类似[a,b,c]++[d,e]的操作来获得[a,b,c,d,e]。这些是连接起来的Haskell列表,但很高兴看到Java中的类似运算符用于数组。你不这么认为吗?这是优雅、简单、通用的,而且实现起来并不那么困难。
如果你愿意,我建议你看看Alexander Hristov在破解OpenJDK编译器方面的工作。他解释了如何修改javac源代码以创建新的运算符。他的示例包括定义一个'**'运算符,其中i**j=Math.pow(i,j)。我们可以用这个例子来实现一个连接两个相同类型数组的运算符。
这样做之后,您就绑定到定制的javac来编译代码,但是任何JVM都可以理解生成的字节码。当然,您可以在源代码级别实现自己的数组连接方法,其他答案中有很多关于如何实现的示例!有这么多有用的运算符可以添加,这一个将是其中之一。
public String[] concat(String[]... arrays)
{
int length = 0;
for (String[] array : arrays) {
length += array.length;
}
String[] result = new String[length];
int destPos = 0;
for (String[] array : arrays) {
System.arraycopy(array, 0, result, destPos, array.length);
destPos += array.length;
}
return result;
}
您可以在两行代码中追加这两个数组。
String[] both = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, both, first.length, second.length);
这是一个快速有效的解决方案,适用于原始类型以及所涉及的两个方法都是重载的。
您应该避免使用涉及ArrayList、流等的解决方案,因为这些解决方案需要分配临时内存,没有任何用处。
对于大型数组,应避免for循环,因为这些循环效率不高。内置方法使用速度极快的块复制函数。