流中的私有排序规则 Java

Private Sorting Rule in a Stream Java

嘿,如果有人有想法,我将非常感激。 我在 Java 流中,我想对我将要返回的列表进行排序。 我需要通过 TradPrefis ( MyObject::getTradPrefix ) 对列表进行排序。 但这太容易了。因为我想按照 TradPrefix exampleTradPrefix_[NUMBER TO SORT]

末尾的数字进行排序

示例:hello_1 test_2 ... still_there_22

这里有一段代码让你想象的更容易。

public LinkedHashSet<WsQuestion> get(String quizId, String companyId) {
    LinkedHashSet<QuizQuestionWithQuestion> toReturn = quizQuestionRepository.findAllQuizQuestionWithQuestionByQuizId(quizId);
    return (toReturn.stream()
            .map(this::createWsQuestion)
            .sorted(comparing(WsQuestion::getTradPrefix.toString().length()))
            .collect(Collectors.toCollection(LinkedHashSet::new)));
}

一种方法就是将 getTradPrefix().toString() 拆分为 _ 并将最右边的值解析为 int,然后使用它对 Stream 进行排序:

public LinkedHashSet<WsQuestion> get(String quizId, String companyId) {
    LinkedHashSet<QuizQuestionWithQuestion> toReturn = quizQuestionRepository.findAllQuizQuestionWithQuestionByQuizId(quizId);
    return toReturn.stream()
        .map(this::createWsQuestion)
        .sorted(Comparator.comparingInt(question -> {
            String[] args = question.getTradPrefix().toString().split("_");
            return Integer.parseInt(args[args.length - 1]);
        }))
        .collect(Collectors.toCollection(LinkedHashSet::new));
}

你可以像这样制作一个小Comparator

  private static final Comparator<String> questionComparator = Comparator.comparingInt(s -> {
    String[] pieces = s.split("_");
    return Integer.parseInt(pieces[pieces.length-1]);
  });

然后在您的 sorted() 中使用它。

拥有一个单独的比较器也会使您的代码更具可读性,因为您将分离关注点。

return toReturn.stream()
            .map(this::createWsQuestion)
            .sorted(questionComparator)
            .collect(Collectors.toCollection(LinkedHashSet::new));

如果我在你那里,我会简单地在 WsQuestion class 上放置一个方法,我们称它为排序顺序:

public int getSortOrder() {
  return Integer.valueOf(tradPrefix.substring(tradPrefix.lastIndexOf("_") + 1));
}

需要 Integer 解析,因为比较字符串会得到 "11" < "2"(感谢 Holger 指出这一点)。 lastIndexOf() 确保在 tradPrefix 中允许使用任意数量的下划线,只要至少有一个即可。

然后使用 Comparator.comparingInt()

简单地创建一个比较器
public LinkedHashSet<WsQuestion> get(String quizId, String companyId) {
  LinkedHashSet<QuizQuestionWithQuestion> toReturn = quizQuestionRepository.findAllQuizQuestionWithQuestionByQuizId(quizId);
  return (toReturn.stream()
      .map(this::createWsQuestion)
      .sorted(comparingInt(WsQuestion::getSortOrder))
      .collect(Collectors.toCollection(LinkedHashSet::new)));
}