第二个条件根据正负排序
时间: 2023-07-06 07:14:36 浏览: 40
如果第二个条件需要按正负排序,可以在Comparator.comparing()方法中使用Lambda表达式自定义比较规则。
假设List中的元素类型为Person,包含两个字段name和score,其中score为一个整数,可以按照以下方式进行排序:
```
List<Person> personList = new ArrayList<>();
// 添加元素到personList中
personList.sort(Comparator.comparing(Person::getName)
.thenComparing((p1, p2) -> {
if (p1.getScore() > 0 && p2.getScore() > 0) {
return Integer.compare(p1.getScore(), p2.getScore());
} else if (p1.getScore() < 0 && p2.getScore() < 0) {
return Integer.compare(p2.getScore(), p1.getScore());
} else {
return Integer.compare(p2.getScore(), p1.getScore());
}
}));
```
这个例子中,我们先按照name字段进行排序,然后按照score字段进行排序。其中,Lambda表达式会根据score字段的正负情况返回不同的比较结果,从而实现按照正负排序。如果score字段都为正数或都为负数,就按照数值大小进行排序,否则按照负数在前、正数在后的顺序进行排序。