【问题标题】:Collection.sort using anonymous class ComparatorCollection.sort 使用匿名类 Comparator
【发布时间】:2018-10-03 22:00:49
【问题描述】:

我没有找到需要的信息,所以我决定创建一个新问题。

我有一个小测试应用程序,我想按值对我的地图进行排序。但是我不明白为什么我不能通过以下方式做到这一点:

    import java.util.Collections;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;

    public class Test {

    public int test(int [] array) {

        Map<Integer, Integer> map = new HashMap<>();
        map.put(1,4);
        map.put(2,3);
        map.put(5,1);
        map.put(7,0);
        map.put(4,4);
        map.put(9,1);

        Collections.sort(map.entrySet(), new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> t, Map.Entry<Integer, Integer> t1) {
                return t.getValue().compareTo(t1.getValue());
            }
        });


        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            sum += entry.getValue();
        }

        return sum;
    }

}

和主类:

public class Main {

    public static void main(String[] args) {

        Test test = new Test();
        System.out.println(test.test(arr));
    }
}

在这种情况下,此应用应返回 14。但我有这个消息 Collections.sort(...) 部分:

集合中的排序(java.util.List、java.util.Comparator)不能应用于 (java.util.Set>, 匿名的 java.util.Comparator>) 原因:不存在类型变量 T 的实例,因此 Set> 符合 List

但如果我将其更改为 Collections.min(...)Collections.max(...)

Collections.min(map.entrySet(), new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> t, Map.Entry<Integer, Integer> t1) {
                return t.getValue().compareTo(t1.getValue());
            }
        });

不会有任何问题。

【问题讨论】:

  • Collections.sort 接受ListSet 不是 List
  • Collections.sort 需要一个List,你给它一个Set。错误信息非常清楚。如果要对地图进行排序,请使用 TreeMap
  • 由于您需要的只是值的总和,因此您无需在他的情况下对它们进行排序。我认为这不是真正的用例,但是,在您的实际用例中,您应该能够避免必须按值对 Map 进行排序(尤其是您不能这样做)

标签: java dictionary collections comparator anonymous-class


【解决方案1】:

Java Map 不能按值排序。但是您可以从 Map.entrySet() 创建一个列表,或者您可能根本不需要集合。

使用列表和比较器。

List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Comparator.comparing(Map.Entry::getValue));

使用流

map.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        //do something here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多