我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
我需要在Java中连接两个字符串数组。
void f(String[] first, String[] second) {
String[] both = ???
}
哪种方法最简单?
当前回答
在Java 8中使用流:
String[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b))
.toArray(String[]::new);
或者像这样,使用flatMap:
String[] both = Stream.of(a, b).flatMap(Stream::of)
.toArray(String[]::new);
要对泛型类型执行此操作,必须使用反射:
@SuppressWarnings("unchecked")
T[] both = Stream.concat(Arrays.stream(a), Arrays.stream(b)).toArray(
size -> (T[]) Array.newInstance(a.getClass().getComponentType(), size));
其他回答
怎么样:
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()]);
}
FunctionalJava库有一个数组包装器类,它为数组提供了方便的方法,如串联。
import static fj.data.Array.array;
…然后
Array<String> both = array(first).append(array(second));
要取回展开的数组,请调用
String[] s = both.array();
看看这个优雅的解决方案(如果您需要除char以外的其他类型,请更改它):
private static void concatArrays(char[] destination, char[]... sources) {
int currPos = 0;
for (char[] source : sources) {
int length = source.length;
System.arraycopy(source, 0, destination, currPos, length);
currPos += length;
}
}
您可以连接每个数组计数。
另一种思考问题的方式。要连接两个或多个数组,必须列出每个数组的所有元素,然后构建一个新数组。这听起来像是创建一个List<T>,然后调用它上的Array。其他一些答案使用ArrayList,这很好。但如何实现我们自己的呢?这并不难:
private static <T> T[] addAll(final T[] f, final T...o){
return new AbstractList<T>(){
@Override
public T get(int i) {
return i>=f.length ? o[i - f.length] : f[i];
}
@Override
public int size() {
return f.length + o.length;
}
}.toArray(f);
}
我相信上面的解决方案相当于使用System.arraycopy的解决方案。然而,我认为这个解决方案有其自身的优点。
另一个基于SilverTab的建议,但它支持x个参数,不需要Java6。它也不是通用的,但我确信它可以是通用的。
private byte[] concat(byte[]... args)
{
int fulllength = 0;
for (byte[] arrItem : args)
{
fulllength += arrItem.length;
}
byte[] retArray = new byte[fulllength];
int start = 0;
for (byte[] arrItem : args)
{
System.arraycopy(arrItem, 0, retArray, start, arrItem.length);
start += arrItem.length;
}
return retArray;
}