HashMap按照value值进行排序
运行结果
e 5.0
a 4.0
c 3.2
d 2.213
b 2.2
程序代码
package GetSemeticWord; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.TreeSet; import java.util.Map.Entry; public class test { /** * @param args */ public static void main(String[] args) { Map<String,Float> map = new HashMap<String,Float>(); map.put("a", 4.0f); map.put("b", 2.2f); map.put("c", 3.2f); map.put("d", 2.213f); map.put("e", 5.0f); Set<Map.Entry<String, Float>> treeSet = new TreeSet<Map.Entry<String, Float>>( new Comparator<Map.Entry<String, Float>>() { public int compare(Map.Entry<String, Float> o1, Map.Entry<String, Float> o2) { Float d1 = o1.getValue(); Float d2 = o2.getValue(); int r = d2.compareTo(d1); if (r != 0) return r; else return o2.getKey().compareTo(o1.getKey()); } }); treeSet.addAll(map.entrySet()); int n=0; for(Entry<String, Float> mapoutReusutby:treeSet){ if(n<10){ mapoutReusutby.getKey(); mapoutReusutby.getValue(); System.out.println(mapoutReusutby.getKey()+"\t"+ mapoutReusutby.getValue()); } } // System.out.println(treeSet); } }