使用 Collections.sort() 对 ArrayList 进行复杂排序?
Complex sorting of ArrayList using Collections.sort()?
我的驱动程序 class 中有一个 ArrayList<Word>
需要排序。 My Word class 有两个属性:
public class Word {
String word;
int count;
}
在我的驱动程序 class 中,它读取 .txt 文件的每个 word
并将其添加到 ArrayList
。我需要先按计数对这个 ArrayList 进行排序,对于具有相同 count
的单词,我需要按字母顺序对它们进行排序 。我可以制作自定义比较器 class 以按计数排序:
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 和覆盖,而不影响它们的一部分。如有任何帮助,我们将不胜感激!
编辑
我正在我的驱动程序中对 ArrayList 进行排序 class:
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())'
我的驱动程序 class 中有一个 ArrayList<Word>
需要排序。 My Word class 有两个属性:
public class Word {
String word;
int count;
}
在我的驱动程序 class 中,它读取 .txt 文件的每个 word
并将其添加到 ArrayList
。我需要先按计数对这个 ArrayList 进行排序,对于具有相同 count
的单词,我需要按字母顺序对它们进行排序 。我可以制作自定义比较器 class 以按计数排序:
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 和覆盖,而不影响它们的一部分。如有任何帮助,我们将不胜感激!
编辑
我正在我的驱动程序中对 ArrayList 进行排序 class:
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())'