如何排序不同的日期?

时间:2018-09-28 09:36:26

标签: java spring

我想按不同的日期(creationDate,displayDate和requestDate)对Foo类中的列表产品进行排序,然后返回Product List。 您有有效的建议吗?

public class Car extend Product {

   String name;

   Date creationDate;

   Product(String name, Date creationDate){
    this.name = name;
    this.creationDate= creationDate;
   }
}

public class Bicycle extend Product {
   String name;

   Date displayDate;

   Bicycle(String name, Date displayDate){
    this.name = name;
    displayDate= displayDate;
   }


}

public class Motorcycle extend Product {
   String name;

   Date requestDate;

   Motorcycle (String name, Date requestDate;{
    this.name = name;
    requestDate=requestDate;;
   }


}

public class ProductConfiguration(){

   List<Car> cars = new ArrayList<>();
   cars.add (new Car ("Jeep", new Date());

   List<Bicycle> bicycles = new ArrayList<>();
   bicycles .add (new Bicycle ("mountainbike", new Date());

   List<Motorcycle > motorcycles = new ArrayList<>();
   motorcycles.add (new Motorcycle ("motorcycles", new Date());

// getter and setter 

}

我想按不同的日期(creationDate,displayDate和requestDate)对Foo类中的列表产品进行排序,然后返回Product List。

public class Foo {


  public List<Product> readData() {  
    ProductConfiguration productConfiguration = new ProductConfiguration();

    List<Product> products = new ArrayList<>();

    products.add(productConfiguration.getCars());
    products.add(productConfiguration.getBicycles());
    products.add(productConfiguration.getMotorcycles());


   public List<Product> sortProductByDate(){
      // I want to sort the list products by date (creationDate, displayDate 
         and requestDate)
         and return the Product List products

   }

  }
}

1 个答案:

答案 0 :(得分:0)

正如@Seelenvirtuose所建议的,我也建议您在产品类别中添加一个日期字段:

public class Product // alternative: create an interface which your classes can implement
{
    private String name;
    private Date date;

    public Product(String name, Date date)
    {
        this.name = name;
        this.date = date;
    }

    // getter / setter
}

然后您可以执行以下操作:

    Product bike = new Product("Bike", new Date()); // just for example. You can create a specialized class Bike with additional fields. This is just for demonstration purposes
    Product car = new Product("Car", new Date()); // see above

    List<Product> productList = new ArrayList<>();
    productList.add(bike);
    productList.add(car);

    productList.sort(new Comparator<Product>()
    {
        @Override
        public int compare(Product o1, Product o2)
        {
            return o1.date.compareTo(o2.date);
        }
    });

   // after this your list is sorted by date