MainActivity如下:
package cn.testhashmapsort; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import android.os.Bundle; import android.app.Activity; /** * Demo描述: * 利用Collections.sort对HashMap里的键值对按照键进行排序 */ public class MainActivity extends Activity { private HashMap<String, Integer> mHashMap; private List<Map.Entry<String, Integer>> mHashMapEntryList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); init(); } private void init(){ mHashMap=new HashMap<String, Integer>(); mHashMap.put("a", 9527); mHashMap.put("z", 7); mHashMap.put("c", 888); mHashMap.put("x", 666); mHashMapEntryList=new ArrayList<Map.Entry<String,Integer>>(mHashMap.entrySet()); System.out.println("-----> 排序前的顺序"); for (int i = 0; i < mHashMapEntryList.size(); i++) { System.out.println(mHashMapEntryList.get(i)); } Collections.sort(mHashMapEntryList, new Comparator<Map.Entry<String,Integer>>() { @Override public int compare(Map.Entry<String,Integer> firstMapEntry, Map.Entry<String,Integer> secondMapEntry) { return firstMapEntry.getKey().compareTo(secondMapEntry.getKey()); } }); System.out.println("-----> 排序后的顺序"); for (int i = 0; i < mHashMapEntryList.size(); i++) { System.out.println(mHashMapEntryList.get(i)); } } }
main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:layout_centerInParent="true" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="测试HashMap的排序" android:textSize="20sp" /> </RelativeLayout>