标签:turn logs man integer blog 实现 .com compareto bsp
1. 给定Map,根据Map中的值从大到小排列
package com.studentmanager.www; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; public class Test12 { public static void main(String[] args) { Map<Integer,Integer> map = new TreeMap<Integer,Integer>(); map.put(5, 3); map.put(6, 4); map.put(2, 2); map.put(1, 7); //这里将map.entrySet()转换成list List<Map.Entry<Integer,Integer>> list = new ArrayList<Map.Entry<Integer,Integer>>(map.entrySet()); //然后通过比较器来实现排序 Collections.sort(list,new Comparator<Map.Entry<Integer,Integer>>() { public int compare(Entry<Integer,Integer> o1, Entry<Integer,Integer> o2) { //升序排序 // return o1.getValue().compareTo(o2.getValue()); //降序排序 return o2.getValue().compareTo(o1.getValue()); } }); for(Map.Entry<Integer,Integer> mapping:list){ System.out.println(mapping.getKey()+":"+mapping.getValue()); } } }
运行结果:
1:7
6:4
5:3
2:2
标签:turn logs man integer blog 实现 .com compareto bsp
原文地址:http://www.cnblogs.com/bosongokay/p/7588879.html