How can I sort a list of pairs of <String, Integer>?
I have a list of Pair combos that store words and their frequency, for example, 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 words, I want the words with the highest frequency to be displayed first.
I tried playing with the Comparable implementation, but most of the examples are not like using a list of pairs
You can use 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 } }); To sort items by decreasing the order of the number
Collections.sort(words, Comparator.comparing(p -> -p.getRight())); This will use the βrightβ of the pair in descending order.
This uses Java 8. It is clear that you are boxing the value and using Integer.compareTo.
However, when analyzing the escape, boxing can be eliminated, and you will not create any objects.
Hi, I think this should work for you.
List<Pair<String, Integer>> words = new ArrayList<Pair<String, Integer>>(); words.add(new Pair<String, Integer>("hello",2)); words.add(new Pair<String, Integer>("hello",1)); words.add(new Pair<String, Integer>("aello",3)); words.sort(new Comparator<Pair<String, Integer>>() { @Override public int compare(Pair<String, Integer> o1, Pair<String, Integer> o2) { if (o1.getValue() > o2.getValue()) { return -1; } else if (o1.getValue().equals(o2.getValue())) { return 0; // You can change this to make it then look at the //words alphabetical order } else { return 1; } } }); System.out.println(words); Use the Java lambda Java 8 in combination with Comparator.comparing (you also need to reverse the order):
import static java.util.Collections.reverseOrder; import static java.util.Comparator.comparing; final List<Pair<String, Integer>> words = new ArrayList<>(); final Comparator<Pair<String, Integer>> c = reverseOrder(comparing(Pair::getValue)); Collections.sort(words, c); The easiest way if you just want to print the values ββin decreasing order of frequency:
words.stream() .sorted(c) .map(Pair::getKey) .forEach(System.out::println);