繁体   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