1. 程式人生 > >利用Sort()方法進行排序

利用Sort()方法進行排序

使用Sort()方法,就需要使用到Comparator比較器,但是他的寫法有多種

  • 直接呼叫Collections.sort()方法,其中list為要排序的集合,new Comparator()為迭代器與比較方法。
List<String> list = new ArrayList<String>(); 
Collections.sort(list, new Comparator() {
     public int compare(final Object a, final Object b) {
          final Object arra = (Object) a;
          final
Object arrb = (Object) b; final int one = Integer.parseInt(arra + ""); final int two = Integer.parseInt(arrb + ""); return two - one; } });
  • 當要比較的集合是實體類時,可以實現實現IComparable介面
public class A implements Comparable<A>{
    /** 序號 **/
    private int num;
    /**要點提示**/
private String tip; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getTip() { return tip; } public void setTip(String tip) { this.tip = tip; } @Override public int compareTo
(A other) { final int one = this.getNum(); final int two = other.getNum(); return two - one; } } List<A> list = new ArrayList<A>(); list.Sort();
  • 針對hashMap的key,value進行排序
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("d", 2);
map.put("c", 1);
map.put("b", 1);
map.put("a", 3);

List<Map.Entry<String, Integer>> infoIds =
    new ArrayList<Map.Entry<String, Integer>>(map.entrySet());

//排序前
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//d 2
//c 1
//b 1
//a 3

//排序
Collections.sort(infoIds, new Comparator<Map.Entry<String, Integer>>() {   
    public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {      
        //return (o2.getValue() - o1.getValue()); 
        return (o1.getKey()).toString().compareTo(o2.getKey());
    }
}); 

//排序後
for (int i = 0; i < infoIds.size(); i++) {
    String id = infoIds.get(i).toString();
    System.out.println(id);
}
//根據key排序
//a 3
//b 1
//c 1
//d 2
//根據value排序
//a 3
//d 2
//b 1
//c 1

總結,以上就是利用Sort()進行相關排序的問題,值得注意的就是IComparable比較器介面的呼叫,然後就是裡面的比較項。