首页 > 代码库 > ArrayList排序
ArrayList排序
下面是排序的代码:
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
ArrayList排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。