簡體   English   中英

Java用數字和字母順序對具有自定義字段的ArrayList進行排序

[英]Java sort ArrayList with custom fields by number and alphabetically

public class Product implements Serializable{

    private String id;
    private String name;
    private double price ;
    private int quantity;

    public Product(String id, String name, double price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "Product{" + "id=" + id + ", name=" + name + ", price=" + price + ", quantity=" + quantity + '}';
    }

我想按價格和名稱對ArrayList<Product>進行排序。 我搜索了很長時間的Google,但無法解決。 Serializable是否可能有問題

您需要實現ComparableComparator接口。 使用Comparator 對用戶定義的對象進行排序,使用可 比較的 對用戶定義的對象進行排序

您可以通過閱讀這些教程來了解兩者之間的區別

考慮您要按照價格對商品進行排序,然后使Product實現Comparable ,如下所示

public class Product implements Comparable<Product>{

    public int compareTo(Product other){
       // your logic here
    }

}

但是等一下...現在我們已經實現了Comparable接口,以使用其價格對對象進行排序,我們如何使用另一個排序序列對它們進行排序? 我們只有一個compareTo()方法,並且不能在同一類中編寫單獨的排序序列。 這是Comparator的角色。 使用Comparator ,您可以定義多個排序序列。

假設我們要使用其價格排序,然后:

public class PriceSorter implements Comparator<Product>{

    public int compare(Product one, Product another){
        int returnVal = 0;

    if(one.getPrice() < another.getPrice()){
        returnVal =  -1;
    }else if(one.getPrice() > another.getPrice()){
        returnVal =  1;
    }else if(one.getPrice() == another.getPrice()){
        returnVal =  0;
    }
    return returnVal;
    }
}

並且您想要另一個排序序列,現在為其名稱,然后:

public class NameSorter implements Comparator<Product>{

        public int compare(Product one, Product another){
            return one.getName().compareTo(another.getName());
        }
}

現在,當您要使用價格排序時

Collections.sort(yourList,new PriceSorter());

如果要使用名稱排序,則

Collections.sort(yourList, new NameSorter());

第二個參數采用Comparator實例,該實例使sort方法知道在對對象進行排序時要遵循的邏輯

Product類實現Comparable接口。

public class Product implements Serializable, Comparable<Product> {

        //Ommitted constructors, fields and accessors

    //This is an ascending sort order
    @Override
    public int compareTo(Product o) {
        int result = this.name.compareToIgnoreCase(o.name);
        if(result != 0){
            return result;
        }else{
            return new Double(this.price).compareTo(new Double(o.price));
        }   
    }
}

然后排序就像將List傳遞給Collections.sort()一樣容易:

public static void main(String[] args) {
    Product p1 = new Product("p1", "shoes", 30.33, 20);
    Product p2 = new Product("p2", "shoes", 20.30, 20);
    Product p3 = new Product("p3", "shoes", 50.33, 20);
    Product p4 = new Product("p4", "socks", 10.50, 20);
    Product p5 = new Product("p5", "socks", 5.40, 20);
    Product p6 = new Product("p6", "socks", 2.34, 20);

    List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);

    System.out.println("Unsorted");
    for(Product product:products){
        System.out.println("Product: " + product.name + " Price: " + product.price);
    }

    Collections.sort(products);

    System.out.println("sorted");
    for(Product product:products){
        System.out.println("Product: " + product.name + " Price: " + product.price);
    }
}

這是 Product 的完整資源 ,該Productmain方法中使用一個排序示例來實現Comparable

import java.io.Serializable;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Product implements Serializable, Comparable<Product> {

    private String id;
    private String name;
    private double price;
    private int quantity;

    public Product(String id, String name, double price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    @Override
    public String toString() {
        return "Product{" + "id=" + id + ", name=" + name + ", price=" + price
                + ", quantity=" + quantity + '}';
    }

    @Override
    public int compareTo(Product o) {
        int result = this.name.compareToIgnoreCase(o.name);
        if(result != 0){
            return result;
        }else{
            return new Double(this.price).compareTo(new Double(o.price));
        }

    }

    public static void main(String[] args) {
        Product p1 = new Product("p1", "shoes", 30.33, 20);
        Product p2 = new Product("p2", "shoes", 20.30, 20);
        Product p3 = new Product("p3", "shoes", 50.33, 20);
        Product p4 = new Product("p4", "socks", 10.50, 20);
        Product p5 = new Product("p5", "socks", 5.40, 20);
        Product p6 = new Product("p6", "socks", 2.34, 20);

        List<Product> products = Arrays.asList(p1,p2,p3,p4,p5,p6);

        System.out.println("Unsorted");
        for(Product product:products){
            System.out.println("Product: " + product.name + " Price: " + product.price);
        }

        Collections.sort(products);

        System.out.println("sorted");
        for(Product product:products){
            System.out.println("Product: " + product.name + " Price: " + product.price);
        }
    }
}

使用Comparator<Product> ,這里是匿名實現的(適用於Java 7和更早版本):

List<Product> list;
Collections.sort(list, new Comparator<Product>() {
    public int compare(Product a, Product b) {
        if (a.getPrice() == b.getPrice())
            return a.getName().compareTo(b.getName()); 
        return a.getPrice() > b.getPrice() ? 1 : a.getPrice() < b.getPrice() ? -1 : 0
    }
});

Java 8有一種更清潔的方式來實現上述目標:

Collections.sort(list, Comparator.comparing(Product::getPrice).thenComparing(Product::getName));

如果這個定義你的產品的“自然秩序”,考慮讓Product實現Comparable<Product> ,並在實現它compareTo()方法Product

您需要實現Comparable接口。 該接口要求您添加一個稱為compareTo(Product other)的函數,在其中編寫代碼以檢查要比較對象的自定義字段。

另外,您可以按照@Prasad Kharkar的建議進行操作,並編寫一個基本上執行相同操作的Comaparator

http://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

據我所知,你沒有這樣的方法,你可以做的是; 擴展Collection的子類並添加排序方法(搜索或冒泡排序等技術,等等)

如果您具有數據庫功能(更多的開銷)*您可以將其放在其中並按順序使用*如果您使用的是JPA,只需將列表轉儲到實體類中

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM