实现 Comparator 接口,重写compare方法,完成自定义排序
int compare(Object o1, Object o2) 返回一个基本类型的整型
如果要按照升序排序,则o1 小于o2,返回-1(负数),相等返回0,01大于02返回1(正数)
如果要按照降序排序,则o1 小于o2,返回1(正数),相等返回0,01大于02返回-1(负数)
使用示例如下:
import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MapSort { public static void main(String[] args) { sortMap();//测试Map排序 } public static Map<String,Double> sortMap(){ Map<String,Double> map = new HashMap<String,Double>(); map.put("100M",(double) 100); map.put("10M",(double) 10); map.put("1000G",(double) 1000000); map.put("10G",(double) 10000); map.put("100T",(double) 100000000); map.put("10T",(double) 10000000); map.put("1T",(double) 1000000); //将map添加到list List<Map.Entry<String,Double>> list = new ArrayList<Map.Entry<String,Double>>(map.entrySet()); System.out.println("排序前:"+list); Collections.sort(list,new Comparator<Map.Entry<String,Double>>() { //从大到小 @Override public int compare(Entry<String, Double> o1, Entry<String, Double> o2) { if(o1.getValue()>o2.getValue()){ return -1; }else if(o1.getValue().equals(o2.getValue())){ String str1 = o1.getKey().substring(o1.getKey().length()-1, o1.getKey().length()); String str2 = o2.getKey().substring(o2.getKey().length()-1, o2.getKey().length()); //因为定义的是Double包装类型,在比较的时候需要用 equals才能判断相等,使用==比较的是对象的地址 if(str1.equals(str2)){ return 0; //数值相同时,比较的是单位,单位从大到小排序 T>G>M }else if((str1.equals("T") && str2.equals("G")) ||( str1.equals("T") && str2.equals("M") )||( str1.equals("G") && str2.equals("M"))){ return -1; }else{ return 1; } }else{ return 1; } } }); System.out.println("排序后(从大到小):"+list);
return map; } }
执行结果:
排序前:[1000G=1000000.0, 1T=1000000.0, 100T=1.0E8, 10T=1.0E7, 10G=10000.0, 100M=100.0, 10M=10.0]
排序后(从大到小):[100T=1.0E8, 10T=1.0E7, 1T=1000000.0, 1000G=1000000.0, 10G=10000.0, 100M=100.0, 10M=10.0]
原文:https://www.cnblogs.com/DFX339/p/12449970.html