enjoy = enjoys.stream().sorted(Comparator.comparing(GoodsEnjoy::getGroundingState, (s1, s2) -> { if (s1.equals(s2)) { return 0; } else if (s1 == 1 || s2 == 5) { return -1; } else if (s1 == 5 || s2 == 1) { return 1; } else if (s1 == 2) { return -1; } else if (s2 == 2) { return 1; } else if (s1 == 0) { return -1; } else { return 1; } })).findFirst().orElse(null);中怎么吧“{ if (s1.equals(s2)) { return 0; } else if (s1 == 1 || s2 == 5) { return -1; } else if (s1 == 5 || s2 == 1) { return 1; } else if (s1 == 2) { return -1; } else if (s2 == 2) { return 1; } else if (s1 == 0) { return -1; } else { return 1; } ”提为变量
时间: 2024-02-10 19:11:57 浏览: 85
【优质】英语专八听力特殊词汇.pdf
可以将这段代码提取为一个lambda表达式或者一个匿名内部类,然后将其作为Comparator.comparing()方法的参数。示例代码如下:
```java
Comparator<GoodsEnjoy> comparator = Comparator.comparing(
GoodsEnjoy::getGroundingState,
(s1, s2) -> {
if (s1.equals(s2)) {
return 0;
} else if (s1 == 1 || s2 == 5) {
return -1;
} else if (s1 == 5 || s2 == 1) {
return 1;
} else if (s1 == 2) {
return -1;
} else if (s2 == 2) {
return 1;
} else if (s1 == 0) {
return -1;
} else {
return 1;
}
}
);
GoodsEnjoy enjoy = enjoys.stream().sorted(comparator).findFirst().orElse(null);
```
这样可以让代码更加清晰易懂,也方便后续的维护和修改。
阅读全文