相关疑难解决方法(0)

按值对地图<键,值>进行排序

我是Java的新手,经常发现我需要对Map<Key, Value>值进行排序.

由于值不是唯一的,我发现自己将其转换keySet为a array,并通过数组排序对该数组进行排序,并使用自定义比较器对与键关联的值进行排序.

有没有更简单的方法?

java sorting collections dictionary

1569
推荐指数
27
解决办法
134万
查看次数

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万
查看次数

标签 统计

java ×2

collections ×1

dictionary ×1

sorting ×1