簡體   English   中英

流Java中的私有排序規則

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM