按照HashMap中value值进行排序
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; /** * 测试HashMap按照value值排序输出 * 先新建一个实现Comparable接口的类,将HashMap的元素用新建类封装,然后构建ArrayList,用Collection.sort排序 * * @author ywf * */ public class Test { public static void main(String[] args) throws Exception { HashMap<String, Integer> input = new LinkedHashMap();// 需要用LinkedHashMap,保证输入的顺序和输出的顺序一致 input.put("ywf", 65); input.put("lqq", 98); input.put("lp", 75); input.put("lj", 90); sort(input); } public static void sort(HashMap<String, Integer> input) { ArrayList<Pair> list = new ArrayList(); for (String id : input.keySet()) { Pair pair = new Pair(id, input.get(id)); list.add(pair); } Collections.sort(list); input.clear(); for (Pair p : list) { input.put(p.id, p.value); } System.out.println(input); } @SuppressWarnings("rawtypes") static class Pair implements Comparable { String id; int value; public Pair(String id, int n) { this.id = id; this.value = n; } @Override public int compareTo(Object o) { // TODO Auto-generated method stub return this.value - ((Pair) o).value; } } }