java - Stream Java 中的私有(private)排序规则

标签 java sorting java-8 java-stream collect

嘿,如果有人有想法,我将非常感激。 我在 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/

相关文章:

java - start.dfs.sh期间的异常

Android 的 Javadoc 生成

java - 根据值对 Map 内的 HashMap 进行排序

java - 通过 java 8 接口(interface)改进 if containsKey in map

java - 为什么 JavaFX API 不包含在 Java 8 J2SE 中?

java - 在 Java 中合并 HTML 文件

java - 使用 Neuroph 神经网络进行图像识别?

sorting - 如何有效地随机排序(洗牌)文件行?

algorithm - 如果它们需要 O(n) 时间对列表进行排序,为什么我们不使用尝试进行排序?

java - 为什么不用导入java.util.streams.Stream就可以进行流操作?