标签:style blog http io ar color os sp java
package com.study; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; public class ComparableTest { public static void main(String[] args) { List<Map<String, String>> list = new ArrayList<Map<String, String>>();
//插入测试数据 Map<String, String> tmp; tmp = new HashMap<String, String>(); tmp.put("price_section_id", "30"); tmp.put("name", "liqiu"); list.add(tmp); tmp = new HashMap<String, String>(); tmp.put("price_section_id", "1"); tmp.put("name", "baoshan"); list.add(tmp); tmp = new HashMap<String, String>(); tmp.put("price_section_id", "3"); tmp.put("name", "yihui"); list.add(tmp); System.out.println(list);
//比较排序-核心代码 Comparator<Map<String, String>> comparator = new Comparator<Map<String, String>>() { public int compare(Map<String, String> s1, Map<String, String> s2) { return new Integer( s1.get("price_section_id").compareTo(s2.get("price_section_id")) ); } }; Collections.sort(list,comparator); System.out.println(list.toString()); } }
[{name=liqiu, price_section_id=30}, {name=baoshan, price_section_id=1}, {name=yihui, price_section_id=3}]
[{name=baoshan, price_section_id=1}, {name=yihui, price_section_id=3}, {name=liqiu, price_section_id=30}]
1. 查看Collections.sort方法:
public static <T> void sort(List<T> list, Comparator<? super T> c) { Object[] a = list.toArray(); Arrays.sort(a, (Comparator)c); ListIterator i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set(a[j]); } }
2. Arrays.sort方法
public static <T> void sort(T[] a, Comparator<? super T> c) { if (LegacyMergeSort.userRequested) legacyMergeSort(a, c); else TimSort.sort(a, c); }
3. TimSort 是一个归并排序做了大量优化的版本。对归并排序排在已经反向排好序的输入时表现O(n^2)的特点做了特别优化。对已经正向排好序的输入减少回溯。对两种情况混合(一会升序,一会降序)的输入处理比较好。
链接:http://baike.baidu.com/view/7780831.htm?fr=aladdin
标签:style blog http io ar color os sp java
原文地址:http://www.cnblogs.com/liqiu/p/4116435.html