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);和 excellent = excellents.stream().sorted(Comparator.comparing(GoodsExcellent::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);这简化一下
时间: 2024-02-10 07:11:57 浏览: 150
可以将这两段代码提取为一个通用的方法,然后复用该方法。示例代码如下:
```java
private static <T, R extends Comparable<? super R>> T findFirstSorted(List<T> list, Function<T, R> keyExtractor) {
Comparator<R> comparator = (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;
}
};
return list.stream().sorted(Comparator.comparing(keyExtractor, comparator)).findFirst().orElse(null);
}
GoodsEnjoy enjoy = findFirstSorted(enjoys, GoodsEnjoy::getGroundingState);
GoodsExcellent excellent = findFirstSorted(excellents, GoodsExcellent::getGroundingState);
```
这样可以让代码更加简洁,也方便后续的维护和修改。
阅读全文