我想选择一组城市数量最少的国家。
然后你想要一个List
国家的顺序或城市数量。为什么不创建一个Country
包含List
城市的类
public class Country{
private final List<String> cityNames = new ArrayList<String>();
private String name;
public Country(String n) { name = n; }
public void addCity(String name){
cityNames.add(name); // omitting validation
}
public List<String> getCityNames(){
List<String> newList = new ArrayList<String>();
newList.addAll(cityNames);
return newList;
}
public int numberOfCities(){
return cityNames.size();
}
public String getName() { return name; }
@Override
public String toString(){
return name + ": Number of Cities = " + cityNames.size();
}
}
现在您可以像这样根据城市数量对国家列表进行排序
... // inside some method
Collections.sort(countries, new Comparator<Country>() {
@Override
public int compare(Country o1, Country o2) {
if(o1.numberOfCities() < o2.numberOfCities()){
return -1;
}
if(o1.numberOfCities() > o2.numberOfCities()){
return 1;
}
return 0;
}
});
我刚刚使用以下方法对此进行了测试(注意:我向 Country 添加了一个“toString()”方法)
public static void main(String[] args) {
Country usa = new Country("USA");
Country canada = new Country("Canada");
Country brazil = new Country("Brazil");
usa.addCity("Lansing");
usa.addCity("New York");
usa.addCity("Los Angeles");
usa.addCity("Houston");
canada.addCity("Toronto");
canada.addCity("Niagra");
brazil.addCity("Vila Velha");
brazil.addCity("Rio");
brazil.addCity("Barbacena");
List<Country> countries = new ArrayList<Country>();
countries.add(usa);
countries.add(brazil);
countries.add(canada);
System.out.println("\n\nAfter Sorting...");
it = countries.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
Collections.sort(countries, new Comparator<Country>() {
@Override
public int compare(Country o1, Country o2) {
if(o1.numberOfCities() < o2.numberOfCities()){
return -1;
}
if(o1.numberOfCities() > o2.numberOfCities()){
return 1;
}
return 0;
}
});
System.out.println("\n\nAfter Sorting...");
it = countries.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
和输出
Before sorting....
USA: Number of Cities = 4
Brazil: Number of Cities = 3
Canada: Number of Cities = 2
After Sorting...
Canada: Number of Cities = 2
Brazil: Number of Cities = 3
USA: Number of Cities = 4