Java中如何基于两个互斥日期字段对对象列表进行降序排序
Java按非空日期字段对Product列表降序排序
核心思路
先为Product类统一提取有效日期(非空的Date1或Date2),再利用Comparator基于该日期执行降序比较。
1. 为Product类添加有效日期获取方法
根据日期字段的实际类型,分两种场景处理:
场景A:日期字段为LocalDateTime类型
如果Product的Date1和Date2已经是LocalDateTime类型,直接添加方法提取有效日期:
public class Product { private LocalDateTime date1; private LocalDateTime date2; // 其他字段、getter/setter省略 public LocalDateTime getEffectiveDate() { // 基于互斥条件,直接返回非空的日期 return date1 != null ? date1 : date2; } }
场景B:日期字段为字符串类型
如果日期是示例中的字符串格式,先定义格式化器完成解析,再提取有效日期:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Locale; public class Product { private String date1; private String date2; // 其他字段、getter/setter省略 // 匹配示例的日期格式:yyyy-MM-dd hh:mm:ss a private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss a", Locale.ENGLISH); public LocalDateTime getEffectiveDate() { String targetDateStr = "null".equals(date1) ? date2 : date1; try { return LocalDateTime.parse(targetDateStr, DATE_FORMATTER); } catch (DateTimeParseException e) { // 按业务需求处理解析失败,比如抛出异常或返回默认值 throw new RuntimeException("日期解析失败: " + targetDateStr, e); } } }
2. 执行排序
方式1:Lambda表达式快速排序
直接调用列表的sort方法,结合反向比较器实现降序:
inventoryList.sort(Comparator.comparing(Product::getEffectiveDate, Comparator.reverseOrder()));
方式2:自定义Comparator类(适合复杂扩展)
如果需要后续调整排序逻辑,可单独定义比较器类:
import java.util.Comparator; class ProductDateDescComparator implements Comparator<Product> { @Override public int compare(Product p1, Product p2) { LocalDateTime d1 = p1.getEffectiveDate(); LocalDateTime d2 = p2.getEffectiveDate(); // 降序排序,通过d2.compareTo(d1)实现反向比较 return d2.compareTo(d1); } } // 使用时: inventoryList.sort(new ProductDateDescComparator());
3. 边界情况处理
如果存在Date1和Date2同时为空/非空的异常对象,可在getEffectiveDate中添加校验:
public LocalDateTime getEffectiveDate() { if (date1 != null && date2 != null) { throw new IllegalStateException("Product对象同时存在两个非空日期"); } if (date1 == null && date2 == null) { throw new IllegalStateException("Product对象无有效日期"); } return date1 != null ? date1 : date2; }
内容的提问来源于stack exchange,提问作者sk001
相关产品推荐
相关产品推荐

