Reputation: 15
public class MergeNames {
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
int na1 = names1.length;
int na2 = names2.length;
String [] result = new String[na1 + na2];
System.arraycopy(names1, 0, result, 0, na1);
System.arraycopy(names2, 0, result, na1, na2);
System.out.println(Arrays.toString(result));
}
}
I created Two Array Object String and Assign Same String values. After need to merge the two String array object into another String array Object.
Note: Without no duplication
I want output like ["Ava", "Emma", "Olivia", "Sophia", "Emma"]
Upvotes: 1
Views: 231
Reputation: 737
You can use Java Stream API
the Stream.of()
. See the example for better understanding.
Reference Code
public class Main {
public static <T> Object[] mergeArray(T[] arr1, T[] arr2)
{
return Stream.of(arr1, arr2).flatMap(Stream::of).distinct().toArray();
}
public static void main(String[] args) {
String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
Object [] result = mergeArray(names1, names2);
System.out.println(Arrays.toString(result));
}
}
Output
[Ava, Emma, Olivia, Sophia]
Upvotes: 1
Reputation: 131
You have small mistake
String [] result = new String[na1 + na2];
not int
Upvotes: 1