【问题标题】:Sorting HashMap<?,?> by key按键排序 HashMap<?,?>
【发布时间】:2011-08-16 21:08:21
【问题描述】:

你好 我需要实现一个接收 HashMap 并通过键 对它的值进行排序(mergeSort)的方法(不使用 TreeMap、SortedMap 或 Collections.Sort 或使用 JAVA 包中的任何排序解决方案)。 我的问题是处理通配符类型... 这是我的实现(由于使用通配符而返回编译错误)

public HashMap<?, ?> mergeSort(HashMap<?, ?> map) {
        if (map.size() < 1) {
            return map;
        }
        // rounds downwards
        int middle = map.size() / 2;
        int location = 0;

        HashMap<?,?> mapLeft = new HashMap<?, ?>();
        HashMap<?,?> mapRight = new HashMap<?, ?>();
        // splitting map
        for (Iterator<?> keyIter = map.keySet().iterator(); keyIter.hasNext();) {
            if (location < middle) {
                mapLeft.put(keyIter, map.get(keyIter));
            } else {
                mapRight.put(keyIter, map.get(keyIter));
            }
            location++;
        }
        // recursive call
        mapLeft = mergeSort(mapLeft);
        mapRight = mergeSort(mapRight);
        return merge(mapLeft, mapRight);
    }

    public HashMap<?, ?> merge(HashMap<?, ?> mapLeft, HashMap<?, ?> mapRight) {
        HashMap<?, ?> result = new HashMap<?, ?>();
        Iterator<?> keyLeftIter = mapLeft.keySet().iterator();
        Iterator<?> keyRightIter = mapRight.keySet().iterator();
        String keyLeft;
        String keyRight;
        while (keyLeftIter.hasNext()) {
            keyLeft = keyLeftIter.next();
            while (keyRightIter.hasNext()) {
                keyRight = keyRightIter.next();

                if (keyLeft.compareTo(keyRight) < 0) {
                    result.put(keyLeft, mapLeft.get(keyLeft));
                    keyLeft = keyLeftIter.next();
                } else {
                    result.put(keyRight, mapRight.get(keyRight));
                    keyRight = keyRightIter.next();
                }
            }
        }
        return result;
    }

感谢您的帮助!

【问题讨论】:

标签: java sorting hashmap


【解决方案1】:

为什么你总是使用?。给孩子起一个名字,比如KeyValue

编辑:您应该完成本教程:Lesson: Generics

【讨论】:

    【解决方案2】:

    这是一个通过键对 Map 进行排序的方法。它利用了Collections.sort(List, Comparator) 方法。

    static Map sortByKey(Map map) {
         List list = new LinkedList(map.entrySet());
         Collections.sort(list, new Comparator() {
              public int compare(Object o1, Object o2) {
                   return ((Comparable) ((Map.Entry) (o1)).getKey())
                  .compareTo(((Map.Entry) (o2)).getKey());
              }
         });
    
        Map result = new LinkedHashMap();
        for (Iterator it = list.iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry)it.next();
            result.put(entry.getKey(), entry.getValue());
        }
        return result;
    } 
    

    【讨论】:

    • 谢谢!由于很多用户说我应该使用 SortedMap,我澄清了我的问题并补充说我不能使用 TreeMap、SortedMap 或 Collections.Sort,也不能使用 JAVA Packages 中的任何排序解决方案。
    【解决方案3】:

    与其他评论者一样,我建议阅读 Java 中的泛型主题。您在合并中所做的是在结果 HashMap 上使用通配符

    HashMap<?, ?> result = new HashMap<?, ?>();
    

    当你在上面加上通配符时,你基本上是在说“我只会读这个”。后来你试图把东西推进去

    result.put(keyLeft, mapLeft.get(keyLeft));
    

    编译器会说“嘿,你刚刚告诉我你只会阅读,现在你想在里面放一些东西......失败

    然后它会生成您的编译时错误。

    解决方案

    不要将通配符放在要修改的集合上。

    【讨论】:

    • 这是一个非常好的解释 - 谢谢。此外,我还澄清了问题并补充说我不能使用 TreeMap、SortedMap 或 Collections.Sort 或使用 JAVA Packages 中的任何排序解决方案。
    【解决方案4】:

    如果您只需满足方法合同,您就可以这样做。

    public HashMap<?, ?> mergeSort(HashMap<?, ?> map) {
        return new LinkedHashMap(new TreeMap(map));
    }
    

    这将对键进行排序并返回 HashMap 的子类。这种方法的设计被打破了,但有时你无法改变。


    如果您正在对地图进行排序,您应该使用像 TreeMap 这样的 SortedMap。 hashmap 不保留顺序,因此无法将其用于合并排序。对 TreeMap 使用合并排序是多余的。

    您不能假设 ? 是 Comparable。你可以写类似的东西。

    public static <K extends Comparable<K>, V> SortedMap<K,V> sort(Map<K,V> map) {
        return new TreeMap<K, V>(map);
    } 
    

    如您所见,这比您的方法更短更简单。这是作业吗?你真的需要使用归并排序吗?

    您遇到的问题是您无法返回 HashMap,因为它不保持顺序,并且您无法返回 TreeMap,因为它会为您对键进行排序,从而使您多余的任何其他内容都变得多余。对于此任务,您只能返回一个 LinkedHashMap,因为它确实保留了顺序,而无需为您进行排序。


    这里是一个使用 LinkedHashMap 的例子。请注意,它不会在运行时创建 Maps 的副本,它会创建一个数组并对其中的部分进行合并排序,直到完全排序为止。

    注意:我使用 TreeMap 作为 SortedMap 来显示其正确排序。 ;)

    public static void main(String... args) throws IOException {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        for(int i=0;i<100;i++)
            map.put((int)(Math.random()*1000), i);
        System.out.println("Unsorted "+map);
        System.out.println("Sorted "+sort(map));
        final String sortedToString = sort(map).toString();
        final String treeMapToString = new TreeMap<Integer, Integer>(map).toString();
        if (!sortedToString.equals(treeMapToString))
            System.out.println(sortedToString+" != \n"+treeMapToString);
    }
    
    public static <K extends Comparable<K>, V> Map<K, V> sort(Map<K, V> map) {
        return mergeSort(map);
    }
    
    // a very bad design idea, but needed for compatibility.
    public static <K extends Comparable<K>, V> HashMap<K, V> mergeSort(Map<K, V> map) {
        Map.Entry<K, V>[] entries = map.entrySet().toArray(new Map.Entry[map.size()]);
        mergeSort0(entries, 0, entries.length);
        HashMap<K, V> ret = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : entries)
            ret.put(entry.getKey(), entry.getValue());
        return ret;
    }
    
    private static <K extends Comparable<K>, V> void mergeSort0(Map.Entry<K, V>[] entries, int start, int end) {
        int len = end - start;
        if (len < 2) return;
        int mid = (end + start) >>> 1;
        mergeSort0(entries, start, mid);
        mergeSort0(entries, mid, end);
        // merge [start, mid) and [mid, end)  to [start, end)
        for(int p = start, l=start, r=mid; p < end && l < r && r < end; p++) {
            int cmp = entries[l].getKey().compareTo(entries[r].getKey());
            if (cmp <=  0) {
                l++;
                // the entry is in the right place already
            } else if (p != r) {
                // we need to insert the entry from the right
                Map.Entry<K,V> e= entries[r];
                // shift up.
                System.arraycopy(entries, p, entries, p+1, r - p);
                l++;
                // move down.
                entries[p] = e;
                r++;
            }
        }
    }
    

    打印

    Unsorted {687=13, 551=0, 2=15, 984=3, 608=6, 714=16, 744=1, 272=5, 854=9, 96=2, 918=18, 829=8, 109=14, 346=7, 522=4, 626=19, 495=12, 695=17, 247=11, 725=10}
    Sorted {2=15, 96=2, 109=14, 247=11, 272=5, 346=7, 495=12, 522=4, 551=0, 608=6, 626=19, 687=13, 695=17, 714=16, 725=10, 744=1, 829=8, 854=9, 918=18, 984=3}
    

    【讨论】:

    • 这是一个很好的答案!但我无法更改我的方法的签名:public HashMap, ?> mergeSort(HashMap, ?> map)。我也不能使用 TreeMap 或 SortedMap(我已经添加了这些更改) - 抱歉不够清楚。
    • 查看我的编辑。正如我所说,HashMap 没有排序或排序。但是,LinkedHashMap 扩展了 HashMap,因此您可以将它作为普通的 HashMap 返回。当然,无论谁坚持认为它是一个具体的类,尤其是一个无法分类的类,都应该有同样不愉快的事情发生在他们身上。 :-P
    • +1 用于捕获下一个编译器投诉,即键可能无法实现 Comparable 的事实。 ? 的关键使问题复杂化,因为尚不清楚解决方案是否必须是通用的。
    猜你喜欢
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    相关资源
    最近更新 更多