Hey, si quelqu'un a une idée je serais vraiment thankfull. Je suis dans un flux Java et je voudrais trier ma liste que je vais retourner. Je dois trier la liste par TradPrefis (MyObject :: getTradPrefix). Mais ce serait trop facile. Parce que je veux trier suivant le numéro à la fin de TradPrefix exampleTradPrefix_ [NOMBRE DE SORT]
Exemple: hello_1 test_2 ... still_there_22
Voici un morceau de code afin que vous puissiez imaginer plus facile.
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)));
}
Si je vous où je voudrais simplement mettre une méthode sur la WsQuestion
classe, Appelons - le l' ordre de tri:
public int getSortOrder() {
return Integer.valueOf(tradPrefix.substring(tradPrefix.lastIndexOf("_") + 1));
}
L' Integer
analyse syntaxique est nécessaire , car la comparaison des chaînes donnerait « 11 » < « 2 » (merci Holger pour avoir signalé). Le lastIndexOf()
fait en sorte que tout nombre de underscores sont autorisés dans tradPrefix
, tant qu'il y a au moins un.
Ensuite, créez simplement un comparotor en utilisant 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)));
}