java - 如何按两个字段排序,其中之一是枚举?

标签 java spring java-8 java-stream

我需要按名称按字母顺序对列表进行排序,然后再按类型对其进行排序,然后将其放在具有特定类型的列表元素的顶部。这是我到目前为止所做的,但它没有按预期工作,它返回仅按名称排序的列表。

  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/

相关文章:

java - 跟踪在另一个 Android 应用中花费的时间

java - Java 8 中的深度优先目录流

java - IntStream 分步迭代

java - org.hibernate.TypeMismatchException : Provided id of the wrong type while fetching data

java - Ldap 单元测试模拟命名枚举

java - 如何下载 JDK 1.8.0_191

java - 用Java将对象强制转换为long

java - 将对象数组从 Angular 发送到 Spring

java - 什么名字| java中的运算符

java - 随时随地掌握 Spring 模型