我需要按名称按字母顺序对列表进行排序,然后再按类型对其进行排序,然后将其放在具有特定类型的列表元素的顶部。这是我到目前为止所做的,但它没有按预期工作,它返回仅按名称排序的列表。
public List<PRDto> present(
List<ParticipantReference> participants) {
return participants.stream()
.map(MAPPER::toDto)
.sorted(Comparator.comparing(PRDto::getName)
.thenComparing(PRDto::getParticipantType, (type1, type2) -> {
if (type1.equals(type2)) {
return 0;
}
if (type2.equals(ParticipantType.S.getDescription())) {
return 1;
}
if (type1.equals(ParticipantType.S.getDescription())) {
return -1;
}
return type1.compareTo(type2);
}))
.collect(toList());
}
这是我的枚举:
@Getter
public enum ParticipantType {
F("F"),
D_F("D+F"),
S("S");
private final String description;
ParticipantType(String description) {
this.description = description;
}
}
最佳答案
为了保持可读性,我不会将比较留在流管道中,而是将其提取到比较器中
public List<PRDto> present(List<ParticipantReference> participants) {
Comparator<PRDto> byType = Comparator.comparing(o -> !o.getType().equals(ParticipantType.S));
Comparator<PRDto> byName = Comparator.comparing(PRDto::getName);
return participants.stream().sorted(byType.thenComparing(byName)).collect(toList());
}
我的回答有不必要的冗余逻辑,谢天谢地@Holger 向我指出了这一点。正如 Holger 在评论中提到的那样,这也可以内联:
return participants.stream().sorted(
Comparator.comparing((PRDto o) -> !o.getType().equals(ParticipantType.S))
.thenComparing(PRDto::getName))
.collect(toList());
关于java - 如何按两个字段排序,其中之一是枚举?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65393395/