Java 对customerAddress进行排序的最佳方法是,所有主地址都位于顶部,其他地址位于底部

Java 对customerAddress进行排序的最佳方法是,所有主地址都位于顶部,其他地址位于底部,java,sorting,collections,Java,Sorting,Collections,我试图对下面的列表进行排序,使主地址位于列表的顶部,然后是其他地址(p.getIsPrimary是一个布尔值,可以为null)。除了下面的方法,还有别的方法吗 List<CustomerAddress> primaryAddress = customerAddresses.stream() .filter(p->Boolean.TRUE.equals(p.getIsPrimary()))

我试图对下面的列表进行排序,使主地址位于列表的顶部,然后是其他地址(p.getIsPrimary是一个布尔值,可以为null)。除了下面的方法,还有别的方法吗

List<CustomerAddress> primaryAddress = customerAddresses.stream()
                                       .filter(p->Boolean.TRUE.equals(p.getIsPrimary()))
                                       .collect(Collectors.toList());

List<CustomerAddress> secondaryAddress = customerAddresses.stream().collect(Collectors.toList());

secondaryAddress.removeAll(primaryAddress);
primaryAddress.addAll(secondaryAddress);```
List primaryAddress=customerAddresses.stream()
.filter(p->Boolean.TRUE.equals(p.getIsPrimary()))
.collect(Collectors.toList());
List secondaryAddress=customerAddresses.stream().collect(Collectors.toList());
secondary address.removeAll(主地址);
主地址addAll(第二地址)```

为什么不使用分区:

Map primarySecondary=
customerAddresses.stream()
.collect(分区方式(p->Boolean.TRUE.equals(p.getIsPrimary()))
;
这将给你:

  • primarySecondary.get(true)
    :所有原色
  • primarySecondary.get(false)
    :所有辅助项

要先对主地址进行排序,请使用将主地址排序在非主地址之前的
比较器调用
sort()
,例如

customerAddresses.sort(Comparator.comparingInt(
a->a.getIsPrimary()!=null&&a.getIsPrimary()?0:1);

代码通过一个
int
值进行排序,这是一种“排序顺序”值,其中0=主要值,1=非主要值。

在上面添加了另一个问题。我们如何按字母顺序排序,然后将主要值放在首位?@PraveenKadri,方法是查看
Comparator
的文档,并使用
然后比较()
方法应用二级排序顺序。或者您可以进行web搜索,例如了解如何进行。我尝试查看thenComparing()以及何时使用Collections.sort(CustomerMailAddresses,Comparator.Comparingit(a->a.getIsPrimary()!=null和&a.getIsPrimary()?0:1)。然后进行比较(CustomerEmailAddress::getEmailAddress));getIsPrimary()正在对未找到的对象进行编译。我想我缺少了一些基本信息推理引擎变得混乱,因此您需要使用
Comparator.comparingInt(a->
Comparator.comparingInt((CustomerEmailAddress a)->
Map<Boolean, List<CustomerAddress>> primarySecondary =
  customerAddresses.stream()
                   .collect(partitioningBy(p -> Boolean.TRUE.equals(p.getIsPrimary()))
;