Merge Names — Java
2 min readDec 26, 2021
Hi guys! I had a test with Java on TestDome, enjoy this code. Below you can see the problem and its solution.
Implement the uniqueNames method. When passed two arrays of names, 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.
The solution:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;public class MergeNames {public static String[] uniqueNames(String[] names1, String[] names2) {List<String> namesList = new ArrayList<String>();namesList = readNames(names1, namesList);
namesList = readNames(names2, namesList);//System.out.println(namesList.toArray().length);return namesList.toArray(new String[0]);
}private static List<String> readNames(String[] names, List<String> namesList) {for (String name : names) {
if (exist(namesList, name) == false) {
namesList.add(name);
}
}return namesList;
}private static boolean exist(List<String> namesList, String name) {for (String nameList : namesList) {
if (nameList.contains(name)) {
return true;
}
}return false;}public static void main(String[] args) {String[] names1 = new String[] { "Ava", "Emma", "Olivia" };
String[] names2 = new String[] { "Olivia", "Sophia", "Emma" };
MergeNames.uniqueNames(names1, names2);
System.out.println(String.join(", ", MergeNames.uniqueNames(names1,names2)));
// should print Ava, Emma, Olivia, Sophia
}
}
Follow me: