I want to pass two arrays of names so that it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.
For example, calling MergeNames.uniqueNames(new String[]{'Ava', 'Emma', 'Olivia'}, new String[]{'Olivia', 'Sophia', 'Emma'})
should return an array containing Ava, Emma, Olivia, and Sophia in any order.
Need to basically implement the uniqueNames
method. Apologies for asking, I am new to Java programming and trying to become a developer by trying coding challenges.
public class MergeNames {
public static String[] uniqueNames(String[] names1, String[] names2) {
throw new UnsupportedOperationException("Waiting to be implemented.");
}
public static void main(String[] args) {
String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
System.out.println(String.join(", ", MergeNames.uniqueNames(names1, names2))); // should print Ava, Emma, Olivia, Sophia
}
}
******MY SOLUTION ANY FEEDBACK WELCOME******
import java.util.*;
public class MergeNames {
public static void main(String[] args) {
String[] names1 = new String[] {"Ava", "Emma", "Olivia"};
String[] names2 = new String[] {"Olivia", "Sophia", "Emma"};
Set<String> mySet1 = new HashSet<String>(Arrays.asList(names1));
Set<String> mySet2 = new HashSet<String>(Arrays.asList(names2));
Set<String> union = new HashSet<String>(mySet1);
union.addAll(mySet2);
System.out.println("Union of the two Sets with no duplicate names : " + union);
}
}
I'm not sure why the uniqueNames function is needed?