Whether you're using arrays, lists, priority queues, or maps โ sorting pairs (or objects with multiple fields) is a common task in Java. This guide will walk you through the best ways to do it, using:
- โ Arrays
- โ
Lists (
ArrayList) - โ PriorityQueue
- โ TreeMap / TreeSet
- โ Custom Objects
- โ Java 8+ functional comparators
๐น 1. Arrays of Primitive Arrays (int[][])
โ Use Case:
Fastest to use in algorithm problems (e.g. LeetCode), with low overhead.
โถ๏ธ Sort by second element (ascending):
int[][] arr = { {1, 5}, {2, 3}, {3, 8}, {4, 1} };
Arrays.sort(arr, (a, b) -> Integer.compare(a[1], b[1]));
โถ๏ธ Sort by second element (descending):
Arrays.sort(arr, (a, b) -> Integer.compare(b[1], a[1]));
โ You cannot use Comparator.comparingInt() here because int[] is not an object with named fields.
๐น 2. List of Arrays (List<int[]>)
Same as arrays but with Collections.sort.
โถ๏ธ Sort by second element ascending:
List<int[]> list = new ArrayList<>();
list.add(new int[]{1, 5});
list.add(new int[]{2, 3});
Collections.sort(list, (a, b) -> Integer.compare(a[1], b[1]));
๐น 3. List of Custom Objects
Define a Pair or any domain object with named fields.
โถ๏ธ Pair class:
class Pair {
int first, second;
Pair(int f, int s) { first = f; second = s; }
}
โถ๏ธ Ascending sort by second:
List<Pair> list = new ArrayList<>();
list.add(new Pair(1, 5));
list.add(new Pair(2, 3));
list.sort(Comparator.comparingInt(p -> p.second));
โถ๏ธ Descending sort:
list.sort(Comparator.comparingInt((Pair p) -> p.second).reversed());
โ Clean and readable โ use this for production-quality code.
๐น 4. PriorityQueue of Pairs
โถ๏ธ With arrays:
PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> Integer.compare(a[1], b[1]));
โถ๏ธ With objects:
PriorityQueue<Pair> pq = new PriorityQueue<>(Comparator.comparingInt(p -> p.second));
๐น 5. Map.Entry<K, V> (like HashMap or TreeMap)
โ Use Case:
When you want to sort a map by value or keys, use Map.Entry.
โถ๏ธ Sort map by value ascending:
Map<String, Integer> map = new HashMap<>();
map.put("a", 3); map.put("b", 1);
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparingInt(Map.Entry::getValue));
โถ๏ธ Descending:
entries.sort(Comparator.comparingInt(Map.Entry::getValue).reversed());
๐น 6. TreeMap and TreeSet Custom Sorting
โ Use Case:
To maintain a continuously sorted collection.
โถ๏ธ TreeMap sorted by custom comparator on keys:
TreeMap<Integer, String> tree = new TreeMap<>(Comparator.reverseOrder());
โถ๏ธ TreeSet with custom objects:
TreeSet<Pair> set = new TreeSet<>(Comparator.comparingInt(p -> p.second));
โ ๏ธ Note: TreeSet requires consistent equals() and compareTo() logic to avoid silent rejection of duplicates.
โ Summary of Comparator Options
| Collection Type | Use Lambda |
comparingInt Works |
Needs Custom Class | Reverse Order |
|---|---|---|---|---|
int[][] / List<int[]>
|
โ Yes | โ No | โ No | โ Yes (manually) |
List<Pair> |
โ Yes | โ Yes | โ Yes | โ Yes |
PriorityQueue<Pair> |
โ Yes | โ Yes | โ Yes | โ Yes |
Map.Entry<K, V> |
โ Yes | โ Yes | โ No | โ Yes |
TreeSet, TreeMap
|
โ Yes | โ Yes | โ Recommended | โ Yes |
๐ Pro Tips
-
Use
Comparator.comparingInt()for clean, readable sorting when dealing with objects. - Use lambdas when working with primitive arrays or quick-and-dirty code.
- Always use
.reversed()when sorting in descending order. - For multiple sort keys (e.g., by value then key), use
thenComparing():
list.sort(Comparator.comparingInt((Pair p) -> p.second)
.thenComparingInt(p -> p.first));
๐งพ Closing Thoughts
Sorting in Java is a versatile tool โ once you understand how to use Comparator, comparingInt, and method references effectively, your code becomes cleaner, safer, and easier to maintain.
Choose the right strategy based on:
- Your data structure (array, list, map)
- Whether you need ascending/descending
- Whether your data has named fields
\
Top comments (0)