[英]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));
}
如果我在哪里,我只是在WsQuestion
类上放一个方法,让我们称之为排序顺序:
public int getSortOrder() {
return Integer.valueOf(tradPrefix.substring(tradPrefix.lastIndexOf("_") + 1));
}
需要Integer
解析,因为比较字符串会给出“11”<“2” (感谢Holger指出这一点)。 lastIndexOf()
确保tradPrefix
中允许任意数量的下划线,只要至少有一个。
然后使用Comparator.comparingInt()
创建一个comparotor
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)));
}
你可以像这样制作一个小型Comparator
:
private static final Comparator<String> questionComparator = Comparator.comparingInt(s -> {
String[] pieces = s.split("_");
return Integer.parseInt(pieces[pieces.length-1]);
});
然后在sorted()
使用它。
拥有一个单独的Comparator也会使您的代码更具可读性,因为您将分离关注点。
return toReturn.stream()
.map(this::createWsQuestion)
.sorted(questionComparator)
.collect(Collectors.toCollection(LinkedHashSet::new));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.