码迷,mamicode.com
首页 > 编程语言 > 详细

ArrayList排序

时间:2014-11-23 14:17:01      阅读:206      评论:0      收藏:0      [点我收藏+]

标签: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

ArrayList排序

标签:style   blog   http   io   ar   color   os   sp   java   

原文地址:http://www.cnblogs.com/liqiu/p/4116435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!