Java Map 按Key排序

时间:2025-04-03 22:22:02
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeSet; public class Demo { private HashMap<Integer, Object> map =new HashMap<Integer, Object>(); private Set<Integer> keySet = map.keySet(); public Object get(Integer key) { return map.get(key); } public void put(Integer key, Object value) { map.put(key, value); } @SuppressWarnings("unchecked") public void sort() { List<Integer> list =new ArrayList<Integer>(map.keySet()); Collections.sort(list, new Comparator<Object>(){ public int compare(Object a, Object b) { return a.toString().toLowerCase().compareTo(b.toString().toLowerCase()); } }); this.keySet = new TreeSet<Integer>(list); } public Set<Integer> keySet() { return this.key } public static void main(String [] args){ Demo map= new Demo(); map.put(11, "加"); map.put(12, "关"); map.put(13, "注"); map.put(10, "添"); map.put(1, "小"); map.put(8, "记"); map.put(9, "得"); map.put(7, "客"); map.put(5, "的"); map.put(6, "博"); map.put(4, "豆"); map.put(3, "糖"); map.put(2, "小"); System.out.println("排序前"); for (Iterator it =map.keySet().iterator();();){ Integer key= (Integer)it.next(); System.out.println( "key[ " + key + "], value[ " + map.get(key) + "] "); } // System.out.println("排序后"); System.out.println( "\n "); map.sort(); for (Iterator it=map.keySet().iterator();();) { Integer key=(Integer)it.next(); System.out.println( "key[ " + key + "], value[ " + map.get(key) + "] "); } } }