3

我目前一直在使用 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 利物浦:体育

4

2 回答 2

2

你可以尝试这样的事情:

public static Map<String, List<Shop>> mySortedMap(final Map<String, List<Shop>> orig)
{
    final Comparator<String> c = new Comparator<String>()
    {
        @Override
        public int compare(final String o1, final String o2)
        {
            // Compare the size of the lists. If they are the same, compare
            // the keys themsevles.
            final int sizeCompare = orig.get(o1).size() - orig.get(o2).size();
            return sizeCompare != 0 ? sizeCompare : o1.compareTo(o2);
        }
    }

    final Map<String, List<Shop>> ret = new TreeMap<String, List<Shop>>(c);
    ret.putAll(orig);
    return ret;
}

解释:TreeMap是 a 的基本实现SortedMap,它可以将键值的比较器作为参数(如果没有比较器作为参数传递,则以键的自然顺序为准)。在这里,我们创建了一个临时比较器,比较作为参数传递的原始映射的列表大小,如果大小相等,它会比较键本身。最后,我们将原始地图中的所有元素注入其中,并将其返回。

于 2012-12-21T16:49:17.147 回答
0

如果您尝试以下操作会怎样:

private static final Comparator<Map.Entry<String, List<Shop>>> CountThenAtoZ =
    new Comparator<Map.Entry<String, List<Shop>>>() {
        @Override
        public int compare(Map.Entry<String, List<Shop>> x, Map.Entry<String, List<Shop>> y) {
            // Compare shop count first. If equal, compare keys alphabetically.
            int cmp = ((Integer)x.getValue().size()).compareTo(y.getValue().size());
            return cmp != 0 ? cmp : x.getKey().compareTo(y.getKey());
        }
    };

...

public String returnAllTownsAndShopsAlphbetically() {

    List<Map.Entry<String, List<Shop>>> entries = new ArrayList<>(atlas.entrySet());
    Collections.sort(entries, CountThenAtoZ);

    String result = "";
    boolean firstTown = true;
    for (Map.Entry<String, List<Shop>> entry : entries) {
        if (!firstTown) result += " | "; else firstTown = false;
        result += entry.getKey() + ": ";

        boolean firstShop = true;
        TreeSet<Shop> sortedShops = new TreeSet<>(new ShopComparatorAtoZ());
        sortedShops.addAll(entry.getValue());
        for (Shop shop : sortedShops) {
            if (!firstShop) result += ", "; else firstShop = false;
            result += shop.getName();
        }
    }

    return result;
}

它的工作方式是首先按照我们想要的顺序创建一个地图集条目列表。我们需要访问键及其关联值来构建正确的排序,因此对实例进行排序ListMap.Entry方便的。

然后我们遍历排序列表来构建结果String,确保在将商店添加到String.

于 2012-12-21T18:12:35.967 回答