Sorting a List of Pair<String, Integer> in Java
In programming, working with pairs of data is a common task, especially when dealing with collections. This article aims to show how to sort a list of these pairs in descending order by frequency so that words with the highest frequency appear first. The examples will use the commons-lang3
library from Apache, which provides the Pair
class.
1. Add the Required Dependency
Since the Pair
class is not included in the JDK, we need to add the commons-lang3
dependency.
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.17.0</version> </dependency>
1.1 Define the List of Pairs
Next, we will define a list of words and their frequencies, utilizing the Pair<String, Integer>
class from the commons-lang3 library. The code below defines a class with a List
of Pair<String, Integer>
, where each pair represents a word and its corresponding frequency.
import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; import java.util.List; public class Sortlistofpairsexamples { // List to store words and their frequencies private final List<Pair<String, Integer>> words = new ArrayList<>(); // Add sample word-frequency pairs to the list public void addWords() { words.add(Pair.of("travel", 50)); words.add(Pair.of("photography", 40)); words.add(Pair.of("adventure", 30)); words.add(Pair.of("lifestyle", 20)); words.add(Pair.of("culture", 15)); } public List<Pair<String, Integer>> getWords() { return words; } }
Here, we have created a list of word-frequency pairs, focusing on tags from a blog post. For instance, the tag “travel” appears 50 times, “photography” appears 40 times, and so on.
2. Using List.sort()
with Comparator
Java provides the List.sort()
method, which can be used with a custom comparator to sort the list based on the second value (frequency) of the Pair
.
import org.apache.commons.lang3.tuple.Pair; import java.util.ArrayList; import java.util.List; import java.util.Comparator; public class Sortlistofpairsexamples { // List to store words and their frequencies private final List<Pair<String, Integer>> words = new ArrayList<>(); // Add sample word-frequency pairs to the list public void addWords() { words.add(Pair.of("travel", 50)); words.add(Pair.of("photography", 40)); words.add(Pair.of("adventure", 30)); words.add(Pair.of("lifestyle", 20)); words.add(Pair.of("culture", 15)); } public List<Pair<String, Integer>> getWords() { return words; } // Sort the list using List.sort() and a custom comparator public void sortWordsByFrequency() { words.sort(Comparator.comparing(Pair<String, Integer>::getRight)); } // Print the sorted list of words public void printSortedWords() { for (Pair<String, Integer> pair : words) { System.out.println(pair.getLeft() + ": " + pair.getRight()); } } public static void main(String[] args) { Sortlistofpairsexamples sorter = new Sortlistofpairsexamples(); sorter.addWords(); sorter.sortWordsByFrequency(); sorter.printSortedWords(); } }
The words.sort()
method is applied to the list, with Comparator.comparing(Pair::getRight)
as the argument. This comparator extracts the frequency (the right element of the pair) and sorts the pairs in ascending order by frequency.
Output is:
To sort the list in descending order, we use the following code snippet:
public void sortWordsByFrequency() { words.sort(Comparator.comparing(Pair<String, Integer>::getRight).reversed()); }
The .reversed()
method ensures that the list is sorted in descending order.
3. Using Collections.sort()
with a Lambda Expression
We can achieve the same result using Collections.sort()
with a lambda expression that simplifies the comparator logic.
import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import java.util.Collections; import java.util.Comparator; public class WordFrequencySorter { // List to store words and their frequencies private final List<Pair<String, Integer>> words = new ArrayList<>(); // Add sample word-frequency pairs to the list public void addWords() { words.add(Pair.of("travel", 50)); words.add(Pair.of("photography", 40)); words.add(Pair.of("adventure", 30)); words.add(Pair.of("lifestyle", 20)); words.add(Pair.of("culture", 15)); } public List<Pair<String, Integer>> getWords() { return words; } // Sort the list using Collections.sort() and a lambda expression public void sortWordsByFrequencyUsingLambda() { Collections.sort(words, Comparator.comparing(p -> p.getRight())); } // Print the sorted list of words public void printSortedWords() { for (Pair<String, Integer> pair : words) { System.out.println(pair.getLeft() + ": " + pair.getRight()); } } public static void main(String[] args) { WordFrequencySorter sorter = new WordFrequencySorter(); sorter.addWords(); sorter.sortWordsByFrequencyUsingLambda(); sorter.printSortedWords(); } }
In this method, sortWordsByFrequencyUsingLambda()
, the Collections.sort()
function is used to sort the list of word-frequency pairs by their frequency. The Comparator.comparing(p -> p.getRight())
lambda expression specifies that the sorting should be based on the frequency, which is the right element of the pair. This code sorts the pairs in ascending order. The output will be the same:
culture: 15 lifestyle: 20 adventure: 30 photography: 40 travel: 50
To achieve descending order, a slight modification can be made by negating the frequency value:
public void sortWordsByFrequencyUsingLambda() { Collections.sort(words, Comparator.comparing(p -> -p.getRight())); }
This approach is slightly more concise than using Comparator.comparing()
.
4. Using Lambda Expressions and Java Streams
Another way to sort the list is by leveraging the power of Java Streams.
// Sort the list using Streams and a lambda expression public List<Pair<String, Integer>> sortWordsByFrequencyUsingStreams() { return words.stream() .sorted(Comparator.comparing(Pair::getRight)) .collect(Collectors.toList()); }
In this method, sortWordsByFrequencyUsingStreams()
, the Java Streams API is used to sort the list of pairs by their frequency. The words.stream()
call converts the list into a stream, and the sorted(Comparator.comparing(Pair::getRight))
method sorts the pairs based on the right element (frequency). The collect(Collectors.toList())
method then gathers the sorted pairs back into a list.
By default, this sorts the pairs in ascending order, so to sort in descending order, we would need to apply Comparator.reversed()
.
5. Conclusion
In this article, we explored different methods to sort a list of Pair<String, Integer>
in Java based on the frequency values. We demonstrated how to use List.sort()
, Collections.sort()
with lambda expressions, and the Streams API to achieve the desired sorting.
6. Download the Source Code
This article covers how to sort a Java list of pairs using various methods.
You can download the full source code of this example here: java list sort pairs