【问题标题】:Collections sort custom comparator集合排序自定义比较器
【发布时间】:2016-11-12 10:34:21
【问题描述】:

我有两门课:

public class Invoice {

private int InvoiceId;
private Customer customer;
private Date invoiceDate;

}

还有

 public class Customer {
   private int customerId;
   private String customerType;
}

customerType 字段可以有三个值:F,H,B

我有一个 Invoice 对象的 arrayList,我想使用 customerType 属性按特定顺序对其进行排序:所有带有 customerType“F”的发票,然后是“H”然后是“B”的发票。

我尝试实现 Comparator 接口,但问题是他的方法 compare 接受 Customer 对象的两个参数,并且以升序或降序方式进行排序。 这是代码:

  Collections sort(invoicesList, new Comparator<Invoice >() {
                 public int compare(Invoice  s1,Invoice s2) {
                        return s1.getCustomer().getCustomerTpe().equalsIgnoreCase("F").compareTo(s2.getCustomer().getCustomerTpe().equalsIgnoreCase("H"))

                      }
                  }
    );

有没有办法以具有三个字段值的特定顺序对我的收藏进行排序? 谢谢

【问题讨论】:

    标签: sorting collections comparator


    【解决方案1】:

    自定义排序顺序的一种方法是首先映射参数,然后对映射的值进行排序。在您的情况下,customerType 的映射可以通过在字符串“FHB”中找到它的索引来完成。在 Java 8 中,这可能表示为

    Collections.sort(invoicesList, Comparator.comparingInt(
        (invoice) -> "FHB".indexOf( invoice.getCustomer().getCustomerType() )));
    

    【讨论】:

    • 我使用的是 java 6,我会尝试用我的 java 版本来实现它。谢谢
    猜你喜欢
    • 2013-11-04
    • 1970-01-01
    • 2011-10-21
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 2021-03-23
    • 1970-01-01
    相关资源
    最近更新 更多