I have two arrays: a=[1,2] b=[3,4] I want to merge them into one array of objects like this: c=[{1,3},{2,4}]
4 Answers
Integer[] arr1 = { 1, 3, 5, 7 };
Integer[] arr2 = { 2, 4, 6, 8 };
Map<Integer, Integer> arr_comb = new HashMap<>();
for (int i = 0; i < arr1.length && i < arr2.length; i++) {
arr_comb.put(arr1[i],arr2[i]);
}
There you go.
4 Comments
Sibin Muhammed A R
The output of this program is "{1=2, 3=4, 5=6, 7=8}", @n3x need's this [{1,3},{2,4}], can you provide the same output.
justanotherguy
@SibinRasiya, the output is correct. That is what you get if you call
toString() on a Map.Sibin Muhammed A R
@n3x is asking for an array of objects!. Here the question is about objects. Can you provide the same console o/p to your answer? His expected o/p is an array "[{1,3},{2,4}]", but he is not sure what kind of objects would be in the array.
justanotherguy
@SibinRasiya, check op's input and my input. Their order is not the same.
You can do this by following code.
int[] a = {1,2};
int[] b = {1,2};
Object[] arrayOfArrays = {a,b};
later say if you want to use it. You can down cast it like below
int[] c = (int[]) arrayOfArrays[0];
int[] d = (int[]) arrayOfArrays[1];
2 Comments
justanotherguy
That is not what the OP wants. He wants
{[1,1][2,2]}Sibin Muhammed A R
Could you please remove the image and copy & paste your answer?
Is not clear what kind of objects OP wants in the array, but the following merges two arrays into an array of map objects, where first array provides the keys and the second the values:
int[] a = {1,2};
int[] b = {3,4};
int result = new Object[a.length];
for (int i = 0; i < a.length; i++ ) {
result[i] = Map.of(a[i],b[i]);
}
System.out.println(Arrays.toString(result));
The output is slightly different, but that's just the representation
[{1=3}, {2=4}]
3 Comments
justanotherguy
The tag is
java-8. Are you sure var will work?OscarRyz
@justanotherguy pff I completely missed that, fixed, Thanks.
OscarRyz
btw
Map.of was added in Java 9, I'll keep it on the answer as I think they can figure that one out.import java.util.ArrayList;
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList <Object> myArray = new ArrayList<Object>();
int[] a = {1,2};
int[] b = {2,3};
String[] c = {"a", "b"};
myArray.add(a);
myArray.add(b);
myArray.add(c);
System.out.println(Arrays.deepToString(myArray.toArray()));
}
}
With ArrayList you can add easily different types of data, in this case using integers and Strings and you can have this result:
3 Comments
Sibin Muhammed A R
Could you please remove the image and copy & paste your answer?
Heterocigoto
@SibinRasiya In the first part you can find the code complete ready to copy and paste
Sibin Muhammed A R
Sometimes images are not visible, always text comes first. Thank you!

{1,3}, what kind of object is that? Is it a custom class? A map? another array? Do you have some code of what you're trying?