How to merge two arrays
Short answer
Create an array of the needed length with the first array inside and copy the second one after it:
void main() {
int[] a = {1, 2, 3};
int[] b = {4, 5};
int[] merged = Arrays.copyOf(a, a.length + b.length);
System.arraycopy(b, 0, merged, a.length, b.length);
IO.println(Arrays.toString(merged));
}Output:
[1, 2, 3, 4, 5]With a stream
IntStream.concat() and Stream.concat() join streams:
void main() {
int[] a = {1, 2};
int[] b = {3, 4};
String[] x = {"a"};
String[] y = {"b", "c"};
IO.println(Arrays.toString(IntStream.concat(Arrays.stream(a), Arrays.stream(b)).toArray()));
IO.println(Arrays.toString(Stream.concat(Arrays.stream(x), Arrays.stream(y)).toArray(String[]::new)));
}Output:
[1, 2, 3, 4]
[a, b, c]Without duplicates
Add distinct() so equal values appear in the result only once:
void main() {
int[] a = {1, 2, 3};
int[] b = {2, 3, 4};
IO.println(Arrays.toString(IntStream.concat(Arrays.stream(a), Arrays.stream(b)).distinct().toArray()));
}Output:
[1, 2, 3, 4]Common mistake
Adding arrays with the + operator. It is not defined for arrays:
void main() {
int[] a = {1};
int[] b = {2};
int[] c = a + b;
}Output:
Main.java:4: error: bad operand types for binary operator '+'Functions used in this recipe
- Arrays.copyOf() — Copies an array into a new one of the same or another length. copyOfRange() copies a part.
- Stream.of() — Creates a stream from the listed values.