代码之家  ›  专栏  ›  技术社区  ›  Angelina

按日期对对象列表排序并应用筛选器

  •  5
  • Angelina  · 技术社区  · 6 年前

    我有付款清单:

    Payment 1
      CountyTaxAmount = 250.00
      CityTaxAmount   = 101.00
      LienAmount      = 0.00
      HazardAmount    = 0.00
      PaymentDueDate  = "2018-06-01"
    
    Payment 2
      CountyTaxAmount = 10.00
      CityTaxAmount = 20.00
      LienAmount      = 0.00
      HazardAmount    = 0.00
      PaymentDueDate = "2018-05-01"
    

    我创建了一个函数,它接受这个列表, currentDueDate . 如果 paymentDueDate 等于 之前 当前决斗 最接近的 当前决斗 ,我想在计算中使用该行。

    由于某种原因,我的同类产品不能正常工作。 有人能解释一下我做错了什么吗? 这是我的代码:

    private EscrowStatusEnum determineEscrowStatus(Payment pcm, LocalDate currentDueDate) {
        EscrowStatusEnum escrowStatus = null;
    
        if(currentDueDate!= null && pcm!=null 
                && pcm.getPayment() != null 
                && !pcm.getPayment().isEmpty()) {
    
            Predicate<Payment> pcmRow = 
                    it->it.getPaymentDueDate()!=null && !it.getPaymentDueDate().isAfter(currentDueDate);
    
            final Payment sortedRow = 
                    pcm.getPayment().stream().sorted((el1, el2) -> el1.getPaymentDueDate().compareTo(el2.getPaymentDueDate())).
                    filter(pcmRow).findFirst().orElse(null);
    
            if(sortedRow != null) {
    
                BigDecimal countyCityLienHazardSum = sortedRow.getCountyTaxAmount().add(sortedRow.getCityTaxAmount()).add(sortedRow.getLienAmount()).add(sortedRow.getHazardAmount());
                BigDecimal countyCityLienSum = sortedRow.getCountyTaxAmount().add(sortedRow.getCityTaxAmount()).add(sortedRow.getLienAmount());
    
                if(countyCityLienHazardSum.compareTo(BigDecimal.ZERO) == 0)
                    escrowStatus = EscrowStatusEnum.NONESCROWED;
                else if(countyCityLienSum.compareTo(BigDecimal.ZERO) > 0 && sortedRow.getHazardAmount().compareTo(BigDecimal.ZERO) == 0 ||
                        countyCityLienSum.compareTo(BigDecimal.ZERO) >= 0 && sortedRow.getHazardAmount().compareTo(BigDecimal.ZERO) > 0)
                    escrowStatus = EscrowStatusEnum.ESCROWED;
            }
        }
    
        return escrowStatus;
    }
    

    当我经过 当前决斗 属于 "2018-06-01" ,我想返回我的代码 Payment 1 .

    目前正在返回 Payment 2 .

    如果我删除 付款2 从我的测试中,然后它返回 付款1 .

    所以排序肯定有问题。

    2 回复  |  直到 6 年前
        1
  •  6
  •   Misha    6 年前

    您的同类返回 最早 日期。你想要的是 最新的 早于截止日期的日期。

    要查找流中的最小值或最大值,请不要使用 sort(...).findFirst() . 使用 max min 相反。在你的情况下:

    sortedRow = pcm.getPayment().stream()
                   .filter(pcmRow)
                   .max(Comparator.comparing(Payment::getPaymentDueDate))
                   .orElse(null);   // not relevant to your question but consider not using nulls so much
    
        2
  •  0
  •   Bohemian    6 年前

    问题出在过滤器中:

    !it.getPaymentDueDate().isAfter(currentDueDate)
    

    这允许付款到期日为 相同的 作为当前到期日期,但您只需要 逾期的 付款。

    将其更改为:

    it.getPaymentDueDate().isBefore(currentDueDate)