我目前一直在使用 Maps,我对如何让我的程序有效运行感到困惑。我可以遍历地图获取键和值,并很容易地按字母顺序和反向字母顺序对它们进行排序,并为此使用了自定义比较器。但是,我现在尝试根据具有最多值的键对地图进行排序。这些值是我创建的对象列表,可以认为是这种情况。
有一个地图集(如目录),其中包含许多城镇(字符串类型的键)。包含商店(列表)。我想对此进行排序,以便首先显示商店最多的城镇,然后按降序排列,二级排序基于城镇的字母顺序,并返回一个代表这个的字符串。
到目前为止,我已经使用了 Comparator 接口,每个类都按字母顺序和反向字母顺序排列,并希望遵循相同的模式进行学习,但这让我完全难过。
例子:
class Atlas {
Map<String, List<Shop> atlas = new HashMap<String, List<Shop>();
void addShop(Shop shop){
//if(Atlas already contains){
get the town and add the shop to it.
}
else{
add the town as the key and the shop as the value in the list
}
}
List<Shop> getAllShopsFromTheGivenTown(String givenTown){
//if(Atlas contains givenTown){
return the givenTown from the List.
}
else{
//Return an ArrayList emptyList
}
}
public String returnAllTownsAndShopsAlphbetically(){
String tmpString = "";
List<String> keys = new LinkedList<String>(atlas.keySet());
TownComparatorAtoZ tc = new TownComparatorAtoZ();
Collections.sort(keys, tc);
for(String town : keys){
List<Shop> shops = new LinkedList<Dealer>(atlas.get(town));
ShopComparatorAtoZ sc = new ShopComparatorAtoZ();
Collections.sort(shop, sc);
for(Shop shop : shops){
if(tmpString.isEmpty()){
tmpString = tmpString + town + ": " + shop.getName();
}
else if(tmpString.contains(town)){
tmpString = tmpString + ", " + shop.getName();
}
else{
tmpString = tmpString + " | " + town + ": " + shop.getName(); }
}
}
return tmpString;
}
}
从上面可以看出(虽然不是最干净和最有效的)按字母顺序返回内容并将重新格式化为字符串生成器。但是,我想知道如何使用比较器来实现我所追求的,如果有人可以提供一个代码片段来解释它的实际作用,我将不胜感激,因为它更多地了解如何做到这一点,而不仅仅是获得一个复制并粘贴代码块,但需要在代码中直观地查看以理解它。
所以输出我想成为
曼彻斯特:m&s, h&m, schuch | 伯明翰:游戏、车身修理厂| 高分辨率照片| CLIPARTO 利物浦:体育