TreeMap排序

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了TreeMap排序相关的知识,希望对你有一定的参考价值。

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapSort {  
    
    public  TreeMap<String,Double> sort(HashMap<String,Double> map){
        ValueComparator bvc =  new ValueComparator(map); 
        TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);  
         sorted_map.putAll(map);  
        return sorted_map;
        
    }
    public static void main(String[] args) {  
  
        HashMap<String,Double> map = new HashMap<String,Double>();  
        map.put("A",99.5);  
        map.put("B",67.4);  
        map.put("C",67.4);  
        map.put("D",67.3);  
        TreeMap<String,Double> sorted_map = new MapSort().sort(map);
        System.out.println("unsorted map: "+map);  
        System.out.println("results: "+sorted_map);  
    }  
}  
  
class ValueComparator implements Comparator<String> {  
  
    Map<String, Double> base;  
    public ValueComparator(Map<String, Double> base) {  
        this.base = base;  
    }  
  
    // Note: this comparator imposes orderings that are inconsistent with equals.      
    public int compare(String a, String b) {  
        if (base.get(a) >= base.get(b)) {  
            return -1;  
        } else {  
            return 1;  
        } // returning 0 would merge keys  
    }  
}


以上是关于TreeMap排序的主要内容,如果未能解决你的问题,请参考以下文章

Map和TreeMap的特点

TreeMap按照value值进行排序

根据Value对Map中的对象进行排序

Java学习笔记5.4.2 Map接口 - TreeMap类

TreeMap理解

TreeMap源码分析