我有一个 ArrayList<Word>
在我需要排序的驱动程序类中。我的 Word 类有两个属性:
public class Word {
String word;
int count;
}
在我的 Driver 类中,它读取并添加每个 word
.txt 文件到 ArrayList
.我需要先按计数对 ArrayList 进行排序,然后对具有相同 count
的单词进行排序,我需要按字母顺序对它们进行排序。我可以制作自定义比较器类以按计数排序:
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);
如果您应该只使用自定义比较器,那么您可以更新比较器以附加与
相同的计数逻辑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())'
关于java - 使用 Collections.sort() 对 ArrayList 进行复杂排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53568882/