java实现的map排序
java实现的map排序,直接上代码:
import java.util.Arrays; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; public class TestSort { // HashMap里面的元素是无序的,要进行排序的话只能是用TreeMap和SortedMap,例如: public static void main(String[] args) throws Exception { Map<Integer, Integer> map = new TreeMap<Integer, Integer>(); map.put(100, 131); map.put(0, 0); map.put(83, 49); map.put(137, 98); map.put(33, 651); map = mapSortByKey(map); System.out.println(map.toString()); } private static SortedMap<Integer, Integer> mapSortByKey( Map<Integer, Integer> unsort_map) { TreeMap<Integer, Integer> result = new TreeMap<Integer, Integer>(); Object[] unsort_key = unsort_map.keySet().toArray(); Arrays.sort(unsort_key); for (int i = 0; i < unsort_key.length; i++) { System.out.println(unsort_map.get(unsort_key[i])); result.put(Integer.parseInt(unsort_key[i].toString()), unsort_map.get(unsort_key[i])); } return result.tailMap(result.firstKey()); } }
打印结果:
651 49 131 98 {0=0, 33=651, 83=49, 100=131, 137=98}