Spring Boot 如何根据两个日期字段对对象列表进行排序

ndasle7k  于 2022-11-05  发布在  Spring
关注(0)|答案(6)|浏览(138)

我正在尝试对Java中的一个对象列表进行排序。每个对象包含两个日期字段Date1Date2。如果Date1不为空,则Date2应为空,如果Date2不为空,则Date1应为空。假设我们的类名为Product,我们有一个对象products的列表inventoryList

products :[
           {
             "name":"abc",
             ...,
             "Date1": "2021-04-18 10:36:34 PM",
             ..., 
             "Date2":"null",
             ...
           },
            "name":"def",
             ...,
             "Date1": "null",
             ...,
             "Date2":"2021-05-17 11:26:34 PM",
             ...
           ]

我想把这个列表按照对象的日期降序排列。提前感谢。

qq24tv8q

qq24tv8q1#

您可以使用Comparator.comparing()方法,指定要在Lambda运算式中排序的属性。

record Product(String name, LocalDate Date1, LocalDate Date2) {}

List<Product> products = Arrays.asList(
    new Product("abc", LocalDate.of(2021, 4, 18), null),
    new Product("def", null, LocalDate.of(2021, 5, 17)));

products.sort(Collections.reverseOrder(
    Comparator.comparing(p -> p.Date1() != null ? p.Date1() : p.Date2())));

products.stream()
    .forEach(System.out::println);

输出:

Product[name=def, Date1=null, Date2=2021-05-17]
Product[name=abc, Date1=2021-04-18, Date2=null]
nwnhqdif

nwnhqdif2#

您可以尝试使用以下方法,使用数据流根据日期对数据进行排序。

  • 在这里,我使用LocalDateTime格式的日期,而不是String格式。*
public class Test {
    public static void main(String[] args) throws ParseException {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a", Locale.ENGLISH);
        Product p1 = new Product("abc", LocalDateTime.parse("2021-04-18 10:36:34 PM",formatter),null);
        Product p2 = new Product("def",null,LocalDateTime.parse("2021-05-17 11:26:34 PM",formatter));

        List<Product> sortedList = Stream.of(p1,p2)
                .sorted(Comparator.comparing(x -> x.getDate1()!=null ? x.getDate1():x.getDate2(),
                        Comparator.nullsFirst(Comparator.reverseOrder())))
                .collect(Collectors.toList());

        System.out.println(sortedList);
    }
}

产品.java

public class Product {

    private String name;
    private LocalDateTime date1;
    private LocalDateTime date2;

    public Product(String name, LocalDateTime date1, LocalDateTime date2) {
        this.name = name;
        this.date1 = date1;
        this.date2 = date2;
    }

    //getters and setters
}

输出:

[Product{name='def', date1=null, date2=2021-05-17T23:26:34},
 Product{name='abc', date1=2021-04-18T10:36:34, date2=null}]
oipij1gg

oipij1gg3#

我建议您这样处理Product类中的选择日期逻辑

import java.util.Date;

public class Product {
    private String name;
    private Date dateOne;
    private Date dateTwo;

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

    public Date getDate() {
        if (this.dateOne != null) {
            return dateOne;
        }
        return dateTwo;
    }

}

然后在Inventory类中,您可以这样排序

public class Inventory {
    public List<Product> sort(List<Product> products) {
        products.sort((Product productOne, Product productTwo) -> {
                if (productOne.getDate().before(productTwo.getDate())) {
                    return -1;
                } else if (productOne.getDate().after(productTwo.getDate())) {
                    return 1;
                } else {
                    return 0;
                }
        });

      return products;
    }
}
a6b3iqyw

a6b3iqyw4#

你可以使用List.sort(Comparator<? super E>)对列表进行原位排序,提供一个Comparator a-一个如何比较两个Products的指令:

products.sort((x, y) -> {/* logics */})

现在,您可以比较xy,即获取并比较它们的日期,执行null检查等,并返回一个整数,其正负号表明x是大于还是小于y

f0ofjuux

f0ofjuux5#

如果你想使用流,并且你不能改变Product-类,你可以实现你自己的Comparator并在流逻辑中使用。
比较器示例:

public class ProductComparator implements Comparator<Product> {

    @Override
    public int compare(Product product1, Product product2) {
        String product1Date = product1.getDate1() != null ? product1.getDate1() : product1.getDate2();
        String product2Date = product2.getDate1() != null ? product2.getDate1() : product2.getDate2();

        return product1Date.compareTo(product2Date);
    }
}

使用流进行的排序可能如下所示:

List<Product> productListSorted = productList.stream()
                .sorted(new ProductComparator())
                .collect(Collectors.toList());

如果只想对列表本身进行排序,可以用途:

productList.sort(new ProductComparator());

请注意,如果两个日期都是null,则此比较器将引发NullPointerException

xytpbqjk

xytpbqjk6#

您可以使用带有自定义比较器的集合进行排序。在自定义比较器中,我检查了哪个日期不为空,然后返回比较结果。

class Product {
    private String name;
    private String date1;
    private String date2;

    public Product(String name, String date1, String date2) {
        this.name = name;
        this.date1 = date1;
        this.date2 = date2;
    }
    public String getName() {
        return this.name;
    }
    public String getDate1() {
        return this.date1;
    }
    public String getDate2() {
        return this.date2;
    }
}

public class SortProductsByDate {

    public static void main(String[] args) {
        List<Product> inventoryList = new ArrayList<>();
        inventoryList.add(new Product("abc", "2021-04-18 10:36:34 PM", null));
        inventoryList.add(new Product("def", null, "2021-05-17 11:26:34 PM"));

        Collections.sort(inventoryList, new Comparator<Product>() {
            @Override
            public int compare(Product p1, Product p2) {
                String d1 = p1.getDate1() == null ? p1.getDate2() : p1.getDate1();
                String d2 = p2.getDate1() == null ? p2.getDate2() : p2.getDate1();

                return d2.compareTo(d1);
            }
            });

        for(Product p : inventoryList) {
            System.out.printf("name: %s\nDate1: %s\nDate2: %s\n\n", p.getName(), p.getDate1(), p.getDate2());
        }
    }
}

控制台输出:

name: def
Date1: null
Date2: 2021-05-17 11:26:34 PM

name: abc
Date1: 2021-04-18 10:36:34 PM
Date2: null

您还可以进一步分离逻辑并清理main方法。在Product类中实现比较器,并为ProductInventory创建一个单独的类。另外,请记住,在重写compareTo()时,还应注意equals()和hashcode()方法,以避免出现任何问题。我在IDE中自动生成了这些字段。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

class Product implements Comparable<Product>{
    private String name;
    private String date1;
    private String date2;

    public Product(String name, String date1, String date2) {
        this.name = name;
        this.date1 = date1;
        this.date2 = date2;
    }

    public String getName() {
        return this.name;
    }

    public String getDate1() {
        return this.date1;
    }

    public String getDate2() {
        return this.date2;
    }

    @Override
    public int compareTo(Product other) {
        String thisDate = this.getDate1() == null ? this.getDate2() : this.getDate1();
        String otherDate = other.getDate1() == null ? other.getDate2() : other.getDate1();
        return otherDate.compareTo(thisDate);
    }

    @Override
    public int hashCode() {
        return Objects.hash(date1, date2, name);
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Product other = (Product) obj;
        return Objects.equals(date1, other.date1) 
                && Objects.equals(date2, other.date2)
                && Objects.equals(name, other.name);
    }

    @Override
    public String toString() {
        String date = date1 == null ? date2 : date1;
        return "[name:" + name + ", date=" + date + "]";
    }
}

class ProductInventory {
    private List<Product> inventoryList;

    public ProductInventory() {
        this.inventoryList = new ArrayList<Product>();
    }

    public List<Product> getInventoryList() {
        return this.inventoryList;
    }

    public void add(Product p) {
        this.inventoryList.add(p);
    }
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for(Product p : inventoryList) {
            sb.append(p.toString());
            sb.append("\n");
        }
        return sb.toString();
    }
}
public class SortProductsByDateDescending {

    public static void main(String[] args) {        
        ProductInventory productInventory = new ProductInventory();

        productInventory.add(new Product("abc", "2021-04-18 10:36:34 PM", null));
        productInventory.add(new Product("def", null, "2022-03-08 03:30:24 AM"));
        productInventory.add(new Product("ghi", null, "2021-05-17 11:26:34 PM"));
        productInventory.add(new Product("jkl", "2025-01-22 01:33:16 AM", null));
        productInventory.add(new Product("mno", "2025-01-22 01:33:16 PM", null));
        productInventory.add(new Product("pqr", "2025-01-22 01:33:17 PM", null));

        Collections.sort(productInventory.getInventoryList());
        System.out.println(productInventory.toString());
    }
}

控制台输出:

[name:pqr, date=2025-01-22 01:33:17 PM]
[name:mno, date=2025-01-22 01:33:16 PM]
[name:jkl, date=2025-01-22 01:33:16 AM]
[name:def, date=2022-03-08 03:30:24 AM]
[name:ghi, date=2021-05-17 11:26:34 PM]
[name:abc, date=2021-04-18 10:36:34 PM]

相关问题