Java中Map按Value排序

时间:2025-04-03 21:49:17
public static void valueUpSort() { // 默认情况,TreeMap按key升序排序 Map<String, Integer> map = new TreeMap<String, Integer>(); ("acb1", 5); ("bac1", 3); ("bca1", 20); ("cab1", 80); ("cba1", 1); ("abc1", 10); ("abc2", 12); // 升序比较器 Comparator<<String, Integer>> valueComparator = new Comparator<<String,Integer>>() { @Override public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) { // TODO Auto-generated method stub return ()-(); } }; // map转换成list进行排序 List<<String, Integer>> list = new ArrayList<<String,Integer>>(()); // 排序 (list,valueComparator); // 默认情况下,TreeMap对key进行升序排序 ("------------map按照value升序排序--------------------"); for (<String, Integer> entry : list) { (() + ":" + ()); } }