我看到了这篇帖子,不得不回答一下,Berwick/Kennebunk是我住过的城镇。你是本地人吗?
无论如何,最简单的方法是使用上面提到的集合操作。这可以保证一些O(log n)的搜索。
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);
}
如果你需要一个更加动态的数据结构,可以使用一个以国家为键,城镇为值的映射。这样,如果你决定通过不同的国家来建立一个大型的城镇数据库,你就可以通过国家来搜索映射并显示城镇。也许可以使用州名代替国家作为键。
生成的数据结构将会像这样:
[USA = [berwick, kennebunk, north berwick, wells], CANADA = [berwick, kennebunk, north berwick, wells], MEXICO = [berwick, kennebunk, north berwick, wells]]
这种数据结构的构建方式可以防止在同一国家/州中出现重复的城镇条目。
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) {
String[] countrys = {"USA", "CANADA", "MEXICO"};
HashMap<String,Set> map = new HashMap<String,Set>();
TreeSet<String> towns = new TreeSet<String>();
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");
for(String country: countrys){
map.put(country, towns);
}
ArrayList<String> mergedValues = mergeMap(map);
}
}
java.util.List
和java.util.stream.Collectors
。 - siegi