嘿,如果有人有想法,我将非常感激。 我在 Java 流中,我想对我将要返回的列表进行排序。 我需要通过 TradPrefis ( MyObject::getTradPrefix ) 对列表进行排序。 但这太容易了。因为我想按照 TradPrefix exampleTradPrefix_[NUMBER TO SORT] 末尾的数字进行排序
例子:你好_1 测试_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));
}
关于java - Stream Java 中的私有(private)排序规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265894/