簡體   English   中英

使用Collections.sort()對ArrayList進行復雜排序?

[英]Complex sorting of ArrayList using Collections.sort()?

我的Driver類中有一個需要排序的ArrayList<Word> 我的Word類有兩個屬性:

public class Word {
    String word;
    int count;
}

在我的Driver類中,它讀取並添加.txt文件的每個wordArrayList 我需要先按count對這個ArrayList進行排序,對於具有相同count的Words,我需要按字母順序對它們進行排序 我可以使自定義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()); 

只是為了改進代碼中的比較器邏輯

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<Word> wordlist排序為:

wordList.sort(comparator);

如果您應該僅使用自定義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())' 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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