java之对字典数据按照键值进行排序

逆序(从大到小排序):

    public static <T> LinkedHashMap<T, Integer> sortByValue2(Map<T, Integer> hm) {
        // HashMap的entry放到List中
        List<Map.Entry<T, Integer>> list =
                new LinkedList<Map.Entry<T, Integer>>(hm.entrySet());

        //  对List按entry的value排序
        Collections.sort(list, new Comparator<Map.Entry<T, Integer>>() {
            public int compare(Map.Entry<T, Integer> o1,
                               Map.Entry<T, Integer> o2) {
                return -((o1.getValue()).compareTo(o2.getValue()));
            }
        });

        LinkedHashMap<T, Integer> res = new LinkedHashMap<>();
        for (Map.Entry<T, Integer> aa : list) {
            res.put(aa.getKey(), aa.getValue());
        }
        return res;
    }

正序(从小到大排序),和逆序相比把,负号改成正号即可:

    public static <T> LinkedHashMap<T, Integer> sortByValue2(Map<T, Integer> hm) {
        // HashMap的entry放到List中
        List<Map.Entry<T, Integer>> list =
                new LinkedList<Map.Entry<T, Integer>>(hm.entrySet());

        //  对List按entry的value排序
        Collections.sort(list, new Comparator<Map.Entry<T, Integer>>() {
            public int compare(Map.Entry<T, Integer> o1,
                               Map.Entry<T, Integer> o2) {
                return ((o1.getValue()).compareTo(o2.getValue()));
            }
        });

        LinkedHashMap<T, Integer> res = new LinkedHashMap<>();
        for (Map.Entry<T, Integer> aa : list) {
            res.put(aa.getKey(), aa.getValue());
        }
        return res;
    }

 

 

 

 

 

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,可以使用Map接口及其实现类来实现数据字典。Map是一种键值对的集合,可以根据键来查找对应的值。常用的Map实现类有HashMap、TreeMap和LinkedHashMap。 1. HashMap:HashMap是基于哈希表实现的,它提供了快速的插入、删除和查找操作。HashMap不保证元素的顺序,即不保证元素的存储顺序和插入顺序一致。 2. TreeMap:TreeMap是基于红黑树实现的,它可以对键进行排序。TreeMap按照键的自然顺序或者自定义的比较器进行排序,并且保持元素的有序状态。 3. LinkedHashMap:LinkedHashMap是HashMap的一个子类,它保持了元素的插入顺序。LinkedHashMap通过双向链表来维护元素的插入顺序,同时使用哈希表来提供快速的查找操作。 使用这些Map实现类,可以方便地实现数据字典功能。例如,可以将键值对存储到Map,然后通过键来获取对应的值。下面是一个简单的示例代码: ```java import java.util.HashMap; import java.util.Map; public class Dictionary { public static void main(String[] args) { // 创建一个HashMap作为数据字典 Map<String, String> dictionary = new HashMap<>(); // 添加键值dictionary.put("apple", "苹果"); dictionary.put("banana", "香蕉"); dictionary.put("orange", "橙子"); // 根据键获取值 String value = dictionary.get("apple"); System.out.println("apple的文名是:" + value); // 遍历字典 for (Map.Entry<String, String> entry : dictionary.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值