关于HashMap指定值进行排序

**

关于HashMap指定值进行排序

在这里插入图片描述

**
我们知道jdk中的API中有个Collections类中有个方法,叫做sort()
排序方法,但是,这个方法需要两个参数,分别是一个列表参数
和一个比较器,而比较器中的T泛型很明显指的是List的元素中的
某一个属性,通过比较器中的compare方法,将我们需要
比较的属性进行比较。
但是,HashMap是一个哈希表,是一种表,
但我们的sort方法需要的是一个列表,
那重点就是该如何将哈希表作为一种泛型,作为列表的一个限定条件,
哈希表中以键值对的方式存储信息,我们可以这样理解,
键值对就是哈希表的元素,而哈希表整体是一个对象,我们直接将
哈希表看成泛型传给列表,这个时候,我们需要用到Map接口中Entry
接口,(当然,关于HashMap排序不止一种方法),我们来看一下jdk
的API对于Entry接口是如何解释的:


public static interface Map.Entry<K,V>映射项(键-值对)。
Map.entrySet 方法返回映射的 collection 视图,
其中的元素属于此类。获得映射项引用的唯一 方法是通过此 
collection 视图的迭代器来实现。这些 Map.Entry 对象仅
 在迭代期间有效;更确切地讲,
 如果在迭代器返回项之后修改了底层映射,
 则某些映射项的行为是不确定的,
 除了通过 setValue加粗样式 在映射项上执行操作之外。 

在这里插入图片描述

也就是说,这个Entry接口可以被看做成一种泛型,这个泛型本身也是一个包含了HashMpa键值对的泛型,我们把这个Map.Entry<T,T>作为一种泛型传给列表,这样,列表中的每个元素是一个键值对,也就是说是一个哈希表。ok直接上代码:
在这里插入图片描述

public class TestHashMapSort {
    
    
    public static void main(String[] args){
    
    
        HashMap<String,Integer> hashMap = new HashMap<>();
        for (int i = 0; i < 10; i++) {
    
    
            hashMap.put("key"+i+ (int)(Math.random()*100),i+(int)(Math.random()*100));
        }
        //我们将哈希表的键值对赋值
        System.out.println(hashMap);
        List<Map.Entry<String,Integer>/**泛型**/> list = new ArrayList<>(hashMap.entrySet());/**返回此映射中包含的映射关系的 Set 视图**/
        //我们来看一下hashMap.entrySet()返回的视图是怎样的
[key072=88, key272=100, key623=51, key964=37, key735=43,
 key40=21, key872=32, key357=11, key550=104, key167=85]
 //其实就是数组的形式


//关键来了:
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
    
    
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
    
    
            //降序
                if (o1.getValue()>o2.getValue()){
    
    //可以看到,对象o1和o2是一个键值对的映射关系,可以通过对象来得到值,当然,也可以得到键。
                    return -1;//当o1比较的某个值大于o2时,返回-1,代表o1这个键值对处于o2的上方
                }
                if (o1.getValue()<o2.getValue()){
    
    
                    return 1;//当o1比较的某个值小于o2时,返回1,代表o1这个键值对处于o2的下方
                }
                else {
    
    
                    return 0;
                }
            }
        });
        for (Map.Entry<String, Integer> ma :
                list) {
    
    
            System.out.println(ma.getKey()+"---->"+ma.getValue());
        }
        System.out.println(list);
    }
}
//以上结果为:
key491=12, key03=33, key759=62, key240=31, key915=88, key598=17, key146=31, key379=20, key673=45, key870=96}
[key491=12, key03=33, key759=62, key240=31, key915=88, key598=17, key146=31, key379=20, key673=45, key870=96]
key870---->96
key915---->88
key759---->62
key673---->45
key03---->33
key240---->31
key146---->31
key379---->20
key598---->17
key491---->12
[key870=96, key915=88, key759=62, key673=45, key03=33, key240=31, key146=31, key379=20, key598=17, key491=12]

Process finished with exit code 0

在这里插入图片描述

おすすめ

転載: blog.csdn.net/dddd2225/article/details/119541909