本套JAVA8教程由于是有英文翻譯過來的,如果有翻譯不對(duì)的地方還請(qǐng)多多包涵赶站。
本節(jié)課先簡(jiǎn)單的介紹下Java8有哪些新特性,對(duì)于Java6/7版本做出哪些更改.那廢話不多說,趕緊開始今天的課程吧.
在本文中,我們將向您展示一些加入Java Array的方法可柿。
Apache Commons Lang – ArrayUtils
Java API
Java 8 Stream
Apache Commons Lang – ArrayUtils
最簡(jiǎn)單的方法是添加Apache Commons Lang庫降宅,并使用ArrayUtils麦锯。
addAll用于連接數(shù)組坛善。
此方法支持基本類型和對(duì)象類型數(shù)組澎媒。
public static void main(String[] args) {
String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};
String[] result = ArrayUtils.addAll(s1, s2);
System.out.println(Arrays.toString(result));
int [] int1 = new int[]{1,2,3};
int[] int2 = new int[]{4,5,6};
int[] result2 = ArrayUtils.addAll(int1, int2);
System.out.println(Arrays.toString(result2));
}
輸出
[a, b, c, d, e, f]
[1, 2, 3, 4, 5, 6]
Java API
純Java API示例,支持原始類型和泛型類型波桩。
public static void main(String[] args) {
String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};
String[] s3 = new String[]{"g", "h", "i"};
String[] result = joinArrayGeneric(s1, s2, s3);
System.out.println(Arrays.toString(result));
int[] int1 = new int[]{1, 2, 3};
int[] int2 = new int[]{4, 5, 6};
int[] int3 = new int[]{7, 8, 9};
int[] result2 = joinArray(int1, int2, int3);
System.out.println(Arrays.toString(result2));
}
static <T> T[] joinArrayGeneric(T[]... arrays) {
int length = 0;
for (T[] array : arrays) {
length += array.length;
}
//T[] result = new T[length];
final T[] result = (T[]) Array.newInstance(arrays[0].getClass().getComponentType(), length);
int offset = 0;
for (T[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
static int[] joinArray(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
final int[] result = new int[length];
int offset = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
輸出
[a, b, c, d, e, f, g, h, i]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Java 8 Stream
Java 8 Stream連接數(shù)組的示例戒努。
public static void main(String[] args) {
String[] s1 = new String[]{"a", "b", "c"};
String[] s2 = new String[]{"d", "e", "f"};
String[] s3 = new String[]{"g", "h", "i"};
//join object type array
String[] result = Stream.of(s1, s2, s3).flatMap(Stream::of).toArray(String[]::new);
System.out.println(Arrays.toString(result));
int [] int1 = new int[]{1,2,3};
int[] int2 = new int[]{4,5,6};
int[] int3 = new int[]{7,8,9};
//join 2 primitive type array
int[] result2 = IntStream.concat(Arrays.stream(int1), Arrays.stream(int2)).toArray();
//join 3 primitive type array, any better idea?
int[] result3 = IntStream.concat(Arrays.stream(int1),
IntStream.concat(Arrays.stream(int2), Arrays.stream(int3))).toArray();
System.out.println(Arrays.toString(result2));
System.out.println(Arrays.toString(result3));
}
輸出
[a, b, c, d, e, f, g, h, i]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
以上就是三種操作數(shù)組的方式, 如果還有別的更好的方式歡迎留言哦
歡迎留言!