Java Map排序

xiaodai 贡献于2012-01-01

作者 qq  创建于2011-07-20 06:02:00   修改者qq  修改于2011-11-09 02:16:00字数1680

文档摘要:
关键词:

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 unsortMap = new HashMap(); unsortMap.put("1", "1"); unsortMap.put("2", "A"); unsortMap.put("3", "2"); unsortMap.put("4", "B"); unsortMap.put("5", "C"); unsortMap.put("6", "c"); unsortMap.put("7", "b"); unsortMap.put("8", "a");   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 sortedMap = sortByComparator(unsortMap);   for (Map.Entry entry : sortedMap.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } }  // sort Map by value 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; } // sort List by string[0] Collections.sort(productDetailList, new Comparator() { public int compare(String[] o1, String[] o2) { String s1=o1[0]; String s2=o2[0]; if(s1==null){ return -1; }else if(s2==null){ return 1; } return s1.toLowerCase().compareTo(s2.toLowerCase()); } }); }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 3 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档