英文:
Best way to sort customerAddress in such a way that all primary address are at the top and others at the bottom
问题
我试图对下面的列表进行排序,使得主地址位于列表顶部,然后是其他地址(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);
英文:
I am trying to sort the below list in such a way that primary address is at the top of the list followed by other address (p.getIsPrimary is a Boolean value and can be null). Is there any other way other than below?
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);```
</details>
# 答案1
**得分**: 0
为什么不使用分区:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
```java
Map<Boolean, List<CustomerAddress>> primarySecondary =
customerAddresses.stream()
.collect(partitioningBy(p -> Boolean.TRUE.equals(p.getIsPrimary())));
这将给您:
- `primarySecondary.get(true)`:所有主要地址。
- `primarySecondary.get(false)`:所有次要地址。
英文:
Why not using a partitioning: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
Map<Boolean, List<CustomerAddress>> primarySecondary =
customerAddresses.stream()
.collect(partitioningBy(p -> Boolean.TRUE.equals(p.getIsPrimary()))
;
This would give you:
primarySecondary.get(true)
: all primaries.primarySecondary.get(false)
: all secondaries.
答案2
得分: 0
为了首先对主要地址进行排序,请调用带有比较器(Comparator
)的 sort()
方法,该比较器将主要地址排在非主要地址之前,例如:
customerAddresses.sort(Comparator.comparingInt(
a -> a.getIsPrimary() != null && a.getIsPrimary() ? 0 : 1));
该代码通过一个 int
值进行排序,这是一种“排序顺序”值,其中 0 表示主要地址,1 表示非主要地址。
英文:
To sort primary addresses first, call sort()
with a Comparator
that orders primary addresses before non-primary addresses, e.g.
customerAddresses.sort(Comparator.comparingInt(
a -> a.getIsPrimary() != null && a.getIsPrimary() ? 0 : 1));
The code sorts by an int
value, a kind of "sort order" value, where 0 = primary and 1 = non-primary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论