Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 800
code511788465541441 Avatar asked Apr 28 '15 12:04

code511788465541441


People also ask

How do you sort 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.

Can we sort string in ArrayList?

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.

How do you sort objects in a list?

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.


1 Answers

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.

like image 23
Peter Lawrey Avatar answered Oct 21 '22 07:10

Peter Lawrey