如何对map中的value进行排序

来源:互联网 发布:搞笑淘宝客服对话 编辑:程序博客网 时间:2024/05/18 02:03
package com.demo.map;

import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
 * map排序
 * @author wang
 *
 */
public class SortMap {

    public static void main(String[] args) {
        Map<String,Integer> map = new HashMap<>();
        map.put("nine",9);
        map.put("six",6);
        map.put("name",6);
        map.put("eight",8);
        map.put("zero",0);
        map.put("one",1);
        map.put("four",4);
        map.put("two",2);
        
        //根据map中的key值排序
        
        sortMap(map);
    }
    
    public static void sortMap(Map<String, Integer> map){
        //获取entrySet
        Set<Map.Entry<String,Integer>> mapEntries = map.entrySet();
        
        for(Entry<String, Integer> entry : mapEntries){
            System.out.println("key:" +entry.getKey()+"   value:"+entry.getValue() );
        }
        
        //使用链表来对集合进行排序,使用LinkedList,利于插入元素
        List<Map.Entry<String, Integer>> result = new LinkedList<>(mapEntries);
        //自定义比较器来比较链表中的元素
        Collections.sort(result, new Comparator<Entry<String, Integer>>() {
            //基于entry的值(Entry.getValue()),来排序链表
            @Override
            public int compare(Entry<String, Integer> o1,
                    Entry<String, Integer> o2) {
                
                return o1.getValue().compareTo(o2.getValue()) ;
            }
            
        });
        
        //将排好序的存入到LinkedHashMap(可保持顺序)中,需要存储键和值信息对到新的映射中。
        Map<String,Integer> linkMap = new LinkedHashMap<>();
        for(Entry<String,Integer> newEntry :result){
            linkMap.put(newEntry.getKey(), newEntry.getValue());            
        }
        //根据entrySet()方法遍历linkMap
        for(Map.Entry<String, Integer> mapEntry : linkMap.entrySet()){
            System.out.println("key:"+mapEntry.getKey()+"  value:"+mapEntry.getValue());
        }
    }

}


结果为:

key:zero  value:0
key:one  value:1
key:two  value:2
key:four  value:4
key:six  value:6
key:name  value:6
key:eight  value:8
key:nine  value:9

总结,这里HashMap使用 内部类Entry<K, V>来存储数据,因此,我们需要对存储有键值对的Entry<K,V>对象进行排序来实现我们的HashMap排序的功能。这里采用对象排序的方法,将

Entry<K,V>对象放入到List集合中,再使用自定义比较器对LinkedList集合排序。由于HashMap不存储key-value对,因此采用LinkedHashMap(可保持顺序)中,需要存储键和值信息对到新的映射中。其中要注意的是:Map集合的key是不允许重复的,一单重复等同于覆盖,我在这里就犯错了。


0 0
原创粉丝点击