I saw this post and had to answer, Berwick/Kennebunk are towns I lived in lol. Are you local?
Anyways The easiest way to do this is with set operations as mentioned above. This gurenttees some O(log n) search .
public List<String> mergeTowns (List<List<String>> list) {
Set<String> uniques = new HashSet<>();
for(List<String> sublist : list) {
uniques.addAll(sublist);
}
return new ArrayList<>(uniques);
}
If your looking for a little more dynamic data structure use a map where country is you key and towns are your values. This way if you decide to build up a big data base of towns by who have different countries you can and then search the map by country to show the towns . Maybe use State instead of country as your key.
The resulting data structure will give up a map like this. when printed.
[USA = [berwick, kennebunk, north berwick, wells], CANADA = [berwick, kennebunk, north berwick, wells], MEXICO = [berwick, kennebunk, north berwick, wells]]
The way the data structure is built up prevents duplicate town entries in the same country/state.
public class Merge {
private static ArrayList<String> mergeMap(HashMap<String, Set> map) {
ArrayList<String> data = new ArrayList();
for(Entry<String, Set> entries : map.entrySet()){
String country = entries.getKey();
Set<String> towns = entries.getValue();
data.add(country+" = "+towns);
}
return data;
}
public static void main(String[] args) {
//Mock data
String[] countrys = {"USA", "CANADA", "MEXICO"};
//Try this way of building your data structure instead of an array list of array list.
HashMap<String,Set> map = new HashMap<String,Set>();
TreeSet<String> towns = new TreeSet<String>();
// Add a couple towns to your set of towns
towns.add("berwick");
towns.add("north berwick");
towns.add("kennebunk");
towns.add("kennebunk");
towns.add("kennebunk");
towns.add("kennebunk");
towns.add("wells");
towns.add("wells");
//With a map you could push a different set of towns to different countries
for(String country: countrys){
map.put(country, towns);
}
//Pass in your map<Country, Towns>
ArrayList<String> mergedValues = mergeMap(map);
}
}