Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Union Operation of two string arrays - Java [duplicate]

Tags:

java

I've two string arrays. For example A = {"ABC", "XYZ", "MNO"} and B = {"ABC", "PQR", "XYZ"} Now I want one string array having {"ABC", "XYZ", "MNO", "PQR"}

How can I do this? Please help me.

like image 915
Krishna Suthar Avatar asked Dec 27 '22 01:12

Krishna Suthar


2 Answers

Get a HashSet and throw all your strings from both arrays in it. Sets do not allow replication so it will only have unique values. Once you are done, you could use the Collections.toArray() to get yourself a string array as a result.

EDIT: It does not seem that you are after the way in which the elements are ordered, however, as per carlspring's suggestion, if you are, just replace the HashSet with a LinkedHashSet.

like image 155
npinti Avatar answered Jan 04 '23 22:01

npinti


This is how to do it:

public class Foo
{

    public static String[] array1 = { "abc", "def", "ghi" };
    public static String[] array2 = { "xyz", "abc" };


    public static void main(String[] args)
    {
        System.out.println("Using List: " + Arrays.toString(usingList()));
        System.out.println("Using Set: " + Arrays.toString(usingSet()));
    }

    public static String[] usingList()
    {
        List<String> list = new ArrayList<String>();
        list.addAll(Arrays.asList(array1));
        list.addAll(Arrays.asList(array2));

        return list.toArray(new String[list.size()]);
    }

    public static String[] usingSet()
    {
        Set<String> set = new LinkedHashSet<String>();
        set.addAll(Arrays.asList(array1));
        set.addAll(Arrays.asList(array2));

        return set.toArray(new String[set.size()]);
    }

}

When using a Set, make sure you're using a LinkedHashSet, if you're expecting array-like ordering -- where the elements remain at the indices you've put them. Set-s tend to internally re-order elements, which might not be what you're looking for.

like image 38
carlspring Avatar answered Jan 04 '23 23:01

carlspring