How can I sort a List of Pair<String,Integer>?

code511788465541441 picture code511788465541441 · Apr 28, 2015 · Viewed 26.9k times · Source

I have a list of commmons Pair that stores words and their frequency like the following

private List<Pair<String, Integer>> words = new ArrayList<Pair<String, Integer>();

I am trying to sort it so that when I iterate over it to print the words, I want the words with the highest frequency to appear first.

I tried playing around with implementing Comparable but most examples are not similar to using a list of Pairs

Answer

user180100 picture user180100 · Apr 28, 2015

You can use a custom Comparator:

Collections.sort(words, new Comparator<Pair<String, Integer>>() {
    @Override
    public int compare(final Pair<String, Integer> o1, final Pair<String, Integer> o2) {
        // TODO: implement your logic here
    }
});