Map按照Value排序(升序,降序)---(Comparator)

时间:2021-09-08 19:24:23

在开发的时候,写一个搜索逻辑,用到好多排序,因为用到了map,数据都放在了map中,这时候需要排序才能用,就有了,这个排序:Map按照Value排序(升序,降序)


public class mapValueCompareSort {    
          public static void main(String[] args) { 
//value降序排 HashMap<String,Double> mapDesc = new HashMap<String,Double>(); ValueComparatorDesc bvcDESC = new ValueComparatorDesc(mapDesc); TreeMap<String,Double> sorted_map_Desc = new TreeMap<String,Double>(bvcDESC); mapDesc.put("A",99.5); mapDesc.put("B",67.4); mapDesc.put("C",67.4); mapDesc.put("D",67.3); mapDesc.put("E",11.0); mapDesc.put("F",-0.1); mapDesc.put("G",0.1); mapDesc.put("H",-99.1); System.out.println("降序=====unsorted map: "+mapDesc); sorted_map_Desc.putAll(mapDesc); System.out.println("降序=====results: "+sorted_map_Desc); //Value升序排 HashMap<String,Double> mapAsc = new HashMap<String,Double>(); ValueComparatorAsc bvcAsc = new ValueComparatorAsc(mapAsc); TreeMap<String,Double> sorted_mapAsc = new TreeMap<String,Double>(bvcAsc); mapAsc.put("A",99.5); mapAsc.put("B",67.4); mapAsc.put("C",67.4); mapAsc.put("D",67.3); mapAsc.put("E",11.0); mapAsc.put("F",-0.1); mapAsc.put("G",0.1); mapAsc.put("H",-99.1); System.out.println("升序====unsorted map: "+mapAsc); sorted_mapAsc.putAll(mapAsc); System.out.println("升序====results: "+sorted_mapAsc); } } class ValueComparatorDesc implements Comparator<String> { Map<String, Double> base; public ValueComparatorDesc(Map<String, Double> base) { this.base = base; } public int compare(String a, String b) { if (base.get(a) >= base.get(b)) { return -1; } else { return 1; } } }class ValueComparatorAsc implements Comparator<String> { Map<String, Double> base; public ValueComparatorAsc(Map<String, Double> base) { this.base = base; } public int compare(String a, String b) { if (base.get(a) <= base.get(b)) { return -1; } else { return 1; } } }


输出结果是:

降序=====unsorted map: {D=67.3, E=11.0, F=-0.1, G=0.1, A=99.5, B=67.4, C=67.4, H=-99.1}
降序=====results: {A=99.5, C=67.4, B=67.4, D=67.3, E=11.0, G=0.1, F=-0.1, H=-99.1}
升序====unsorted map: {D=67.3, E=11.0, F=-0.1, G=0.1, A=99.5, B=67.4, C=67.4, H=-99.1}
升序====results: {H=-99.1, F=-0.1, G=0.1, E=11.0, D=67.3, C=67.4, B=67.4, A=99.5}


这个排序的时候,值可以double的,
上篇文章Map按照Value排序(升序,降序)--string,这个由于Collections.sort只支持String,String的类型 ,给value排序的时候就只能整数的排序,因为不满足我的需求,就重新写了一个,整理一下,以后可以用到的时候,直接用