'How to merge 2 arrays in array of objects

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}]



Solution 1:[1]

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.

Solution 2:[2]

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];
    

Solution 3:[3]

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}]

Solution 4:[4]

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:

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 justanotherguy
Solution 2
Solution 3
Solution 4 Heterocigoto