这是我的哈希图:
Map<String,String> unsortMap = new HashMap<String,String>()
此地图包含如下值
unsortMap.put("18/06/2012", "18/06/2012");
unsortMap.put("19/06/2012", "19/06/2012");
unsortMap.put("20/06/2012", "20/06/2012");
unsortMap.put("26/06/2012", "26/06/2012");
unsortMap.put("27/06/2012", "27/06/2012");
unsortMap.put("04/07/2012", "04/07/2012");
unsortMap.put("13/07/2012", "13/07/2012");
unsortMap.put("29/06/2012", "29/06/2012");
我用来对该地图进行排序的代码如下:
package samples;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class SortMapExample{
public static void main(String[] args) {
System.out.println("Unsort Map......");
Map<String,String> unsortMap = new HashMap<String,String>();
unsortMap.put("18/06/2012", "18/06/2012");
unsortMap.put("19/06/2012", "19/06/2012");
unsortMap.put("20/06/2012", "20/06/2012");
unsortMap.put("26/06/2012", "26/06/2012");
unsortMap.put("27/06/2012", "27/06/2012");
unsortMap.put("04/07/2012", "04/07/2012");
unsortMap.put("13/07/2012", "13/07/2012");
unsortMap.put("29/06/2012", "29/06/2012");
Iterator iterator=unsortMap.entrySet().iterator();
for (Map.Entry entry : unsortMap.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
System.out.println("Sorted Map......");
Map<String,String> sortedMap = sortByComparator(unsortMap);
for (Map.Entry entry : sortedMap.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
private static Map sortByComparator(Map unsortMap) {
List list = new LinkedList(unsortMap.entrySet());
//sort list based on comparator
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
//put sorted list into map again
Map sortedMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
我得到的结果是这样的:
Sorted Map......
Key : 04/07/2012 Value : 04/07/2012
Key : 13/07/2012 Value : 13/07/2012
Key : 18/06/2012 Value : 18/06/2012
Key : 19/06/2012 Value : 19/06/2012
Key : 20/06/2012 Value : 20/06/2012
Key : 26/06/2012 Value : 26/06/2012
Key : 27/06/2012 Value : 27/06/2012
Key : 29/06/2012 Value : 29/06/2012
我希望结果如下所示:(地图也应按月份排序)
18/06/2012
19/06/2012
20/06/2012
26/06/2012
27/06/2012
29/06/2012
04/07/2012
13/07/2012
请帮我解决这个问题?