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
Approach: Store the pairs in an array using a user-defined Pair class. Override the comparator method to sort the array according to the first element. Sort the array according to the first element.
Approach: An ArrayList can be Sorted by using the sort() method of the Collections Class in Java. This sort() method takes the collection to be sorted as the parameter and returns a Collection sorted in the Ascending Order by default.
For sorting the list with the given property, we use the list's sort() method. The sort() method takes the list to be sorted (final sorted list is also the same) and a comparator.
To sort the elements by decreasing order of number
Collections.sort(words, Comparator.comparing(p -> -p.getRight()));
This will use the "right" of the pair in descending order.
This uses Java 8. Notionally you are boxing the value and using Integer.compareTo.
However, with escape analysis, the boxing can be eliminated and you mgiht not be creating any objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With