流Java中的私有排序规则

Jul*_*der 5 java sorting collect java-8 java-stream

嘿,如果有人有想法,我会非常感激.我在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)));
}
Run Code Online (Sandbox Code Playgroud)

Mag*_*lex 3

如果我只是在WsQuestion类上放置一个方法,我们将其称为排序顺序:

public int getSortOrder() {
  return Integer.valueOf(tradPrefix.substring(tradPrefix.lastIndexOf("_") + 1));
}
Run Code Online (Sandbox Code Playgroud)

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)));
}
Run Code Online (Sandbox Code Playgroud)