Complex sorting of ArrayList using Collections.sort()?

jeispyun :

I have an ArrayList<Word> in my Driver class that needs to be sorted. My Word class has two attributes:

public class Word {
    String word;
    int count;
}

In my Driver class, it reads and adds each word of a .txt file to the ArrayList. I need to sort this ArrayList first by count, and for the Words that have the same count, I need to sort them alphabetically. I could make custom Comparator class to sort by count:

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

And it works. But now I am stuck with how to keep this sorted ArrayList as such and operate one more sorting.. because usually using Collections.sort() affects the whole ArrayList and override, not affecting part of them. Any help would be appreciated!

Edit

I am sorting my ArrayList as such in my Driver class:

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

Just to improve the comparator logic in your code

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

Your overall comparator should be something like :

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

using which you can sort your List<Word> wordlist as:

wordList.sort(comparator);

If you are supposed to be using the custom Comparator only, then you can update the compartor to append the same count logic as

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());
        }
    }
}

and then further use that for sorting :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=95498&siteId=1