日期:2014-05-20 浏览次数:20697 次
package com.test; import java.util.*; public class MultiSortTest { public static void main(String[] args) { List<Map<String, String>> list = new ArrayList<Map<String, String>>(); Map<String, String> map = new HashMap<String, String>(); map.put("time", "2012-2-1"); map.put("price", "203"); map.put("title", "J2EE ebook "); list.add(map); Map<String, String> map1 = new HashMap<String, String>(); map1.put("time", "2012-3-1"); map1.put("price", "103"); map1.put("title", "think in java "); list.add(map1); HashMap<String, String>[] maps = new HashMap[list.size()]; list.toArray(maps); System.out.println("sort by time:"); sort(maps, "time"); printMaps(maps); System.out.println("\nsort by price:"); sort(maps, "price"); printMaps(maps); System.out.println("\nsort by title:"); sort(maps, "title"); printMaps(maps); } public static void printMaps(HashMap<String, String>[] maps ) { for(HashMap<String, String> map:maps) { System.out.println(map.get("time")+"\t"+map.get("price")+"\t"+map.get("title")); } } public static void sort(HashMap<String, String>[] maps,final String key) { Arrays.sort(maps,new Comparator<HashMap<String,String>>(){ public int compare(HashMap<String, String> o1, HashMap<String, String> o2) { //利用比较hashcode来排序不太准确,实际应用中要分析的更详细点 return o1.get(key).hashCode()-o2.get(key).hashCode(); } }); } }
------解决方案--------------------