• map按值排序


    package com.zhilei.test;

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

    public class mapValueCompareSort {
    public static void main(String[] args) {

    HashMap<String, Double> mapDesc = new HashMap<String, Double>();
    ValueComparator bvcDESC = new ValueComparator(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);


    sorted_map_Desc.putAll(mapDesc);

    System.out.println("降序=====results: " + sorted_map_Desc);

    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("宽", 99.5);
    mapAsc.put("B", 67.4);
    mapAsc.put("C", 67.4);
    mapAsc.put("D", 67.3);
    mapAsc.put("r", 11.0);
    mapAsc.put("rt", -0.1);
    mapAsc.put("ee", 0.1);
    mapAsc.put("cc", -99.1);

    System.out.println("升序====unsorted map: " + mapAsc);

    sorted_mapAsc.putAll(mapAsc);

    System.out.println("升序====results: " + sorted_mapAsc);

    }
    }

    class ValueComparator implements Comparator<String> {
    Map<String, Double> base;

    public ValueComparator(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;
    }
    }

    }
  • 相关阅读:
    sed点滴
    JS中使用window.open("url?param="+paramvalue)传递参数出现乱码
    java算法之插入排序法
    NodeJS中的事件模块EventEmitter
    转载: 通过Object.prototype.toString 精确判断对象的类型
    CommonJS的模块规范
    Windows Store App之文件选择器、文件保存器和文件夹选择器
    vue日期格式化
    Linux下安装Apache
    ubuntu 安装 ES 以及集群的搭建
  • 原文地址:https://www.cnblogs.com/leigepython/p/10118946.html
Copyright © 2020-2023  润新知