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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With