8
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>按价格和名称排序。我用谷歌搜索了很长时间,但我无法解决。Serializable是否有问题

4

5 回答 5

28

您需要为您的目的实现ComparableComparator接口。使用 Comparator 对用户定义的对象进行排序,并使用 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 方法知道在对对象进行排序时遵循什么逻辑的实例

于 2013-08-19T10:56:37.733 回答
5

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));
        }   
    }
}

然后排序就像传递Listto一样简单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其中Comparable包含一个排序示例main

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);
        }
    }
}
于 2013-08-19T11:04:54.200 回答
3

使用 a 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

于 2013-08-19T11:01:47.293 回答
1

您需要实现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/

于 2013-08-19T10:59:56.477 回答
0

据我所知,你没有这样的方法,你能做的是;扩展 Collection 的子类并添加排序方法(搜索或冒泡排序等技术)

如果您有数据库设施(更多开销)*您可以将它放在那里并使用 order by *如果您正在使用 JPA,只需将您的列表转储到实体类中

于 2013-08-19T11:01:13.167 回答