相关疑难解决方法(0)

TreeMap按值排序

我想写一个比较器,让我按值而不是默认的自然顺序对TreeMap进行排序.

我试过这样的东西,却找不到出了什么问题:

import java.util.*;

class treeMap {
    public static void main(String[] args) {
        System.out.println("the main");
        byValue cmp = new byValue();
        Map<String, Integer> map = new TreeMap<String, Integer>(cmp);
        map.put("de",10);
        map.put("ab", 20);
        map.put("a",5);

        for (Map.Entry<String,Integer> pair: map.entrySet()) {
            System.out.println(pair.getKey()+":"+pair.getValue());
        }
    }
}

class byValue implements Comparator<Map.Entry<String,Integer>> {
    public int compare(Map.Entry<String,Integer> e1, Map.Entry<String,Integer> e2) {
        if (e1.getValue() < e2.getValue()){
            return 1;
        } else if (e1.getValue() == e2.getValue()) {
            return 0;
        } else {
            return -1;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我想我要问的是:我可以Map.Entry传递给比较器吗?

java

124
推荐指数
6
解决办法
24万
查看次数

可以按值的顺序迭代的映射

我需要一个可以按其值的递减顺序迭代的Map .是否有像Apache Commons或Guava这样的标准库提供这种地图?

java collections map apache-commons guava

16
推荐指数
2
解决办法
9291
查看次数

标签 统计

java ×2

apache-commons ×1

collections ×1

guava ×1

map ×1