dataList.sort( Comparator.comparing( ShopeePushOrderDto::getOrderProfit, Comparator.nullsLast(Comparator.reverseOrder()) ) ); orderProfit这个字段有可能正值,负值,空,现在负值之间没有倒序
时间: 2025-04-04 11:07:40 浏览: 30
### 负值与正值混合情况下的倒序排序
在 Java 中,`Comparator.nullsLast(Comparator.reverseOrder())` 是一种常见的方法来处理包含 `null` 的数据集合并实现倒序排序。然而,在涉及负数和正数的情况下,需要特别注意数值的比较逻辑。
以下是针对 `dataList` 进行倒序排序的具体解决方案:
#### 解决方案代码
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
List<ShopeePushOrderDto> dataList = new ArrayList<>();
// 初始化测试数据
dataList.add(new ShopeePushOrderDto(-10));
dataList.add(new ShopeePushOrderDto(5));
dataList.add(new ShopeePushOrderDto(null)); // 添加 null 测试
dataList.add(new ShopeePushOrderDto(-3));
dataList.add(new ShopeePushOrderDto(8));
// 排序逻辑
dataList.sort(Comparator.comparing(
(ShopeePushOrderDto dto) -> dto.getOrderProfit(),
Comparator.nullsLast(Comparator.reverseOrder())
));
// 输出结果
for (ShopeePushOrderDto item : dataList) {
System.out.println(item.getOrderProfit());
}
}
}
class ShopeePushOrderDto {
private Integer orderProfit;
public ShopeePushOrderDto(Integer orderProfit) {
this.orderProfit = orderProfit;
}
public Integer getOrderProfit() {
return orderProfit;
}
}
```
#### 说明
上述代码实现了以下功能:
- **处理空值**:通过 `Comparator.nullsLast()` 将 `null` 放置在列表最后[^1]。
- **倒序排列**:利用 `Comparator.reverseOrder()` 对正数和负数进行降序排列。
对于负数和正数的情况,Java 默认会按照数值大小进行比较(即 `-10 < -3 < 5 < 8`),因此无需额外调整其自然顺序即可满足需求。
---
### 链表反转的相关扩展
如果目标是从尾到头打印链表中的节点值,则可以参考如下代码片段:
#### 链表反转代码
```java
import java.util.ArrayList;
import java.util.List;
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public class ReverseLinkedList {
public int[] reversePrint(ListNode head) {
List<Integer> list = new ArrayList<>();
ListNode current = head;
while (current != null) {
list.add(current.val);
current = current.next;
}
int size = list.size();
int[] result = new int[size];
for (int i = 0; i < size; i++) {
result[i] = list.get(size - 1 - i);
}
return result;
}
}
```
此代码基于引用[2]进行了优化,使用了更简洁的方式完成链表反转操作。
---
### 寻找两个链表的第一个公共结点
当涉及到寻找两个单向链表的第一个公共结点时,可以通过哈希表存储其中一个链表的所有节点,并逐一检查另一个链表是否存在相同的节点。
#### 查找公共结点代码
```java
import java.util.HashMap;
public class CommonNodeFinder {
public ListNode findFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashMap<ListNode, Boolean> map = new HashMap<>();
ListNode current1 = pHead1;
while (current1 != null) {
map.put(current1, true);
current1 = current1.next;
}
ListNode current2 = pHead2;
while (current2 != null) {
if (map.containsKey(current2)) {
return current2;
}
current2 = current2.next;
}
return null;
}
}
```
该算法的时间复杂度为 O(n+m),其中 n 和 m 分别表示两个链表的长度[^3]。
---
阅读全文
相关推荐


















