This post will discuss how to combine two arrays of different types into a single new object array in Java. The new array should contain all the first array elements, followed by all the second array elements.

1. Using Stream API

We can combine two arrays of different types in Java using Stream.flatMap() method. The idea is to first create a stream of each array using the Stream.of() method and use the Stream.flatMap() method to combine two streams into one. Finally, we can use the Stream.toArray() method to convert the stream into an object array. Here is an example:

Download  Run Code

 
Alternatively, we can create a stream of each array using the Stream.of() method and use the Stream.concat() method to concatenate two streams into one. Finally, we can use the Stream.toArray() method to convert the stream into an array. Here is an example:

Download  Run Code

2. Using System.arraycopy() method

Another option is to use System.arraycopy() method to combine two arrays of different types in Java. The idea is to first create an array of objects that can store both types of elements. Then, we can use the System.arraycopy() method to copy the elements from the source arrays to the destination array. Here is an example:

Download  Run Code

3. Using Collections.addAll() method

We can also use the Collections.addAll() method to create a collection of objects for holding both types of elements. Here is an example of combining an array of String and an array of Integer into a List<Object> using Collections.addAll() method:

Download  Run Code

4. Using Guava’s ObjectArrays.concat() method

Guava provides a simple and convenient way to combine two arrays of different types in Java using the ObjectArrays.concat() method. This method takes two arrays as arguments and returns a new array containing the elements of both arrays. Here is an example of its usage:

Download Code

That’s all about combining two arrays of different types in Java.