【发布时间】:2019-12-23 05:52:36
【问题描述】:
我有这个:
List<City> cities = new ArrayList<>();
cities.add(new City("SF","USA"));
cities.add(new City("Agra","India"));
cities.add(new City("Mumbai","India"));
cities.add(new City("NY","USA"));
所需输出:
List<"Some thing"> combined = new ArrayList();
combined is like this :
USA
SF
NY
India
Mumbai
Agra
我使用了这种方法:
public class ListBreak {
public static void main(String[] args) {
List<City> cities = new ArrayList<>();
cities.add(new City("SF","USA"));
cities.add(new City("Agra","India"));
cities.add(new City("Mumbai","India"));
cities.add(new City("NY","USA"));
List<ABC> abcs = new ArrayList<>();
HashMap<Country,List<City>> countryListHashMap= new HashMap<>();
// way one
for (City city:cities) {
Country coutry= new Country(city.countryName);
if(!countryListHashMap.containsKey(coutry))
{
countryListHashMap.put(coutry,new ArrayList<>());
}
List<City> list = countryListHashMap.get(coutry);
list.add(city);
countryListHashMap.put(coutry,list);
}
for (Map.Entry<Country,List<City>> entrySet:countryListHashMap.entrySet()) {
abcs.add(entrySet.getKey());
abcs.addAll(entrySet.getValue());
}
System.out.println(abcs);
}
static class City implements ABC{
String cityName;
String countryName;
public City(String cityName, String countryName) {
this.cityName = cityName;
this.countryName = countryName;
}
}
static class Country implements ABC{
String countryName;
public Country(String countryName) {
this.countryName = countryName;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Country)) return false;
Country country = (Country) o;
return countryName.equals(country.countryName);
}
@Override
public int hashCode() {
return Objects.hash(countryName);
}
}
}
任何更好、更清洁、更快的方法
【问题讨论】:
-
它已经在那里了
-
即使有人使用比较器根据您的 India、Mumbai 和 Agra 对您进行排序,那么美国的城市也会失败。
-
如果您的疑问尚未消除,请告诉我们。
标签: java performance java-8 coding-style