首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java Vector 排序實作:自訂 Comparator 依指定欄位排序

     編輯:Java 相關知識

前言

Vector 是舊版同步化列表,現多建議使用 ArrayList。但若需維護舊代碼,仍可透過 Collections.sort(list, comparator) 進行排序。本文示範如何實作 Comparator 依物件欄位降序排列。

程式碼

import java.util.*;

class Elem {
    private int val;
    public Elem(int v) { val = v; }
    public int get() { return val; }
}

class MyCompare implements Comparator<Elem> {
    @Override
    public int compare(Elem e1, Elem e2) {
        // 降序:大者在前
        return Integer.compare(e2.get(), e1.get());
    }
}

public class VectorSortDemo {
    public static void main(String[] args) {
        List<Elem> v = new Vector<>();
        v.add(new Elem(1));
        v.add(new Elem(22));
        v.add(new Elem(3));
        v.add(new Elem(14));

        Collections.sort(v, new MyCompare());
        v.forEach(e -> System.out.println(e.get()));
    }
}

輸出結果

22
14
3
1

重點

  • Comparator.compare(o1, o2) 回傳負值表示 o1 < o2(升序),正值表示 o1 > o2(降序)。
  • Java 8 可簡寫為 Collections.sort(v, Comparator.comparing(Elem::get).reversed())。
  • Vector 所有方法皆同步,多執行緒環境下無需額外加鎖,但效能較 ArrayList 低。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved