Search code examples
javaarrayscomparisonstring-length

Create new array by comparing two arrays of String of different length


I have two arrays of String:

arr1 = {"i", "b", "v", "d", "y", "z", "u", "a"}
arr2 = {"i", "b", "v", "y", "u", "z", "a"}

I want to create a new array "arr3" from "arr1" and "arr2". The trick is that if there is missing element in arr2, then I want to keep a empty element and also, keep the same order of elements in arr2.

In my example :

  • Element 'd' is missing in arr2 so it will arr3[i] = ""
  • Elements 'u' and 'z' are inversed compared to "arr1", but it does not matter as I want to maintain the order of "arr2"

Here is my code:

public static void main(String[] args){

    String[] arr1 = {"q", "b", "v", "d", "y", "z", "u", "a"};
    String[] arr2 = {"q", "b", "v", "y", "u", "z", "a"};

    String[] arr3 = new String[arr1.length];

    for(int i = 0;i<arr1.length ; i++) {
        if(getIndex(arr1[i], arr2) == -1)
            arr3[i] = "";
        else
            if (i < arr2.length)
               arr3[i] = arr2[i];   
    }
}

public static int getIndex(String element, String[] array) {
    for(int i=0;i<array.length;i++) {
        if(array[i].contentEquals(element))
            return i;
    }
    return -1;
}

The output of the above code is :

arr3 = {"q", "b", "v", "", "u", "z", "a"}

The element 'y' is missed from arr2.


Solution

  • I'm guessing you would be fine with using standard library functions.

    Try the following:

    public static void main(String[] args)
    {
    
        String[] arr1 = {"q", "b", "v", "d", "y", "z", "u", "a"};
        String[] arr2 = {"q", "b", "v", "y", "u", "z", "a"};
    
        String[] arr3 = new String[arr1.length];
    
        List array1 = new ArrayList(Arrays.asList(arr1));
        List array2 = new ArrayList(Arrays.asList(arr2));
    
        array1.forEach(element -> {
            if(!array2.contains(element))
            {
                int elementPosition = array1.indexOf(element);
                array2.add(elementPosition, "");
            }
        });
    
        // prints [q, b, v, , y, u, z, a]
        System.out.println(array2);
    }
    

    If you want, you can use another arraylist (instead of array2) to add the empty characters. You can also convert the final ArrayList into String[] if that is what you need.

    Hope this helps !

    UPDATE: Although I removed streams, there is a lambda expression in forEach, which will not work with 1.7. PFB the plain java code compatible with Java 1.7 for the forEach part.

        // Without using Lambdas
        for(Object element : array1)
        {
            String s = (String) element;
            if(!array2.contains(s))
            {
                int elementPosition = array1.indexOf(element);
                array2.add(elementPosition, "");
            }
        }