Java HashMap两种简便排序方法解析

2022-10-09,,,,

这篇文章主要介绍了java hashmap两种简便排序方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

hashmap的储存是没有顺序的,而是按照key的hashcode实现.

key=手机品牌,value=价格,这里以这个例子实现按名称排序和按价格排序.

map phone=new hashmap();
    phone.put("apple",8899);
    phone.put("samsung",7000);
    phone.put("meizu",2698);
    phone.put("xiaomi",1800);
    system.out.println(phone);

直接输出hashmap得到的是一个无序map(不是arraylist那种顺序型储存)

1. 按key排序

对名称进行排序,首先要得到hashmap中键的集合(keyset),并转换为数组,这样才能用arrays.sort()进行排序

set set=phone.keyset();
    object[] arr=set.toarray();
    arrays.sort(arr);
    for(object key:arr){
      system.out.println(key);
    }

得到排序好的键值

最后利用hashmap.get(key)得到键对应的值即可

    for(object key:arr){
      system.out.println(key+": "+phone.get(key));
    }

得到的打印的结果

2.按value排序

对价格进行排序,首先需要得到hashmap中的包含映射关系的视图(entryset),
如图:

将entryset转换为list,然后重写比较器比较即可.这里可以使用list.sort(comparator),也可以使用collections.sort(list,comparator)

转换为list

 list<map.entry<string, integer>> list = new arraylist<map.entry<string, integer>>(phone.entryset()); //转换为list

使用list.sort()排序

list.sort(new comparator<map.entry<string, integer>>() {
     @override
     public int compare(map.entry<string, integer> o1, map.entry<string, integer> o2) {
       return o2.getvalue().compareto(o1.getvalue());
     }
   });

使用collections.sort()排序

collections.sort(list, new comparator<map.entry<string, integer>>() {
      @override
      public int compare(map.entry<string, integer> o1, map.entry<string, integer> o2) {
        return o2.getvalue().compareto(o1.getvalue());
      }
    });

两种方式结果输出

//for循环
     for (int i = 0; i < list.size(); i++) {
      system.out.println(list.get(i).getkey() + ": " + list.get(i).getvalue());
    }   
 //for-each循环
      for (map.entry<string, integer> mapping : list){
      system.out.println(mapping.getkey()+": "+mapping.getvalue());
    }

遍历打印输出

//for
    for (int i = 0; i < list.size(); i++) {
      system.out.println(list.get(i).getkey() + ": " +list.get(i).getvalue());
    }
    system.out.println();
    //for-each
    for (map.entry<string, integer> mapping : list) {
      system.out.println(mapping.getkey() + ": " +mapping.getvalue());
    }

结果

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

《Java HashMap两种简便排序方法解析.doc》

下载本文的Word格式文档,以方便收藏与打印。