【问题标题】:Complex sorting of ArrayList using Collections.sort()?使用 Collections.sort() 对 ArrayList 进行复杂排序?
【发布时间】:2019-05-03 06:41:46
【问题描述】:

我的 Driver 类中有一个 ArrayList<Word> 需要排序。我的 Word 类有两个属性:

public class Word {
    String word;
    int count;
}

在我的 Driver 类中,它读取 .txt 文件的每个 word 并将其添加到 ArrayList。我需要先按计数对这个 ArrayList 进行排序,对于具有相同 count 的单词,我需要按字母顺序对它们进行排序。我可以制作自定义 Comparator 类按计数排序:

public class SortByFreq implements Comparator<Word>{
    @Override
    public int compare(Word w1, Word w2) {
        return -(w1.count - w2.count); // Sort as descending order
    } 
}

而且它有效。但是现在我被困在如何保持这个排序的 ArrayList 并再进行一次排序。因为通常使用 Collections.sort() 会影响整个 ArrayList 并覆盖,而不影响其中的一部分。任何帮助将不胜感激!

编辑

我在我的 Driver 类中对我的 ArrayList 进行排序:

Collections.sort(wordList, new SortByFreq()); 

【问题讨论】:

    标签: java sorting arraylist collections comparator


    【解决方案1】:

    只是为了改进代码中的比较器逻辑

    public class SortByFreq implements Comparator<Word> {
        @Override
        public int compare(Word w1, Word w2) {
            return Integer.compare(w2.getCount(), w1.getCount());
        }
    }
    

    你的整体比较器应该是这样的:

    Comparator<Word> comparator = Comparator.comparingInt(Word::getCount).reversed()
                                            .thenComparing(Word::getWord);
    

    使用它您可以将List&lt;Word&gt; wordlist 排序为:

    wordList.sort(comparator);
    

    如果您应该只使用自定义比较器,那么您可以更新比较器以附加与

    相同的计数逻辑
    static class SortByFreqAndAlphabetically implements Comparator<Word> {
        @Override
        public int compare(Word w1, Word w2) {
            if (w1.getCount() != w2.getCount()) {
                return Integer.compare(w2.getCount(), w1.getCount());
            } else {
                return w1.getWord().compareTo(w2.getWord());
            }
        }
    }
    

    然后进一步使用它进行排序:

    wordList.sort(new SortByFreqAndAlphabetically()); // similar to 'Collections.sort(wordList, new SortByFreqAndAlphabetically())' 
    

    【讨论】:

    • 使用以下解决方案创建了一个相同的小提琴,以防万一有人想看到它运行:tpcg.io/egtJxO
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-07
    • 2017-05-07
    • 1970-01-01
    • 2017-03-05
    • 2013-04-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多