Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sorting 集合排序自定义比较器_Sorting_Collections_Comparator - Fatal编程技术网

Sorting 集合排序自定义比较器

Sorting 集合排序自定义比较器,sorting,collections,comparator,Sorting,Collections,Comparator,我有两门课: public class Invoice { private int InvoiceId; private Customer customer; private Date invoiceDate; } 及 customerType字段可以有三个值:F、H、B 我有一个发票对象的arrayList,我想使用customerType属性按特定顺序对其进行排序:customerType为“F”的所有发票,然后是带有“H”的发票,然后是带有“B”的发票 我试图实现Comparator接

我有两门课:

public class Invoice {

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

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

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

我试图实现Comparator接口,但问题是他的方法compare接受客户对象的两个参数,排序是以升序或降序的方式进行的。 代码如下:

  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"))

                      }
                  }
    );
Collections排序(invoicesList,newcomparator(){
公共整数比较(发票s1、发票s2){
返回s1.getCustomer().GetCustomerType().equalsIgnoreCase(“F”).compareTo(s2.getCustomer().GetCustomerType().equalsIgnoreCase(“H”))
}
}
);
有没有一种方法可以用三个filed值按特定顺序对我的集合进行排序?
自定义排序顺序的一种方法是首先映射参数,然后根据映射的值进行排序。在您的例子中,
customerType
的映射可以通过在字符串“FHB”中查找其索引来完成。在Java8中,这可以表示为

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

我正在使用Java6,我将尝试用我的java版本实现它。谢谢
Collections.sort(invoicesList, Comparator.comparingInt(
    (invoice) -> "FHB".indexOf( invoice.getCustomer().getCustomerType() )));