【发布时间】:2021-10-28 13:25:34
【问题描述】:
我试图按我作为值的数组列表的长度对哈希图进行排序。我的哈希图是:
HashMap<Integer, ArrayList<Integer>> NameofMap = new HashMap<Integer, ArrayList<Integer>>();
我一直在尝试使用内联比较器和 collections.sort,但它似乎对我的对象类型不满意,我不知道如何解决它。任何帮助将不胜感激,到目前为止我的代码如下:
Collections.sort(NameofMap.values(), new java.util.Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
return o1.size().compareTo(o2.size());
}
});
【问题讨论】:
-
你有什么错误?
GroupInts与NameOfMap是什么? -
“我正在尝试对 hashmap 进行排序..”让我们停在这里。 HashMap 中元素的顺序取决于键的数量及其哈希码,而不是值的任何属性。您可能想要创建单独的集合,该集合可以像
LinkedHashMap一样进行排序,从而保留插入顺序。更多信息Sort a Map<Key, Value> by values
标签: java sorting arraylist hashmap