DEV Community

Dev Cookies
Dev Cookies

Posted on

๐Ÿง  Mastering Sorting of Pairs and Custom Objects in Java: A Complete Guide

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]));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Sort by second element (descending):

Arrays.sort(arr, (a, b) -> Integer.compare(b[1], a[1]));
Enter fullscreen mode Exit fullscreen mode

โŒ 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]));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 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; }
}
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ 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));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Descending sort:

list.sort(Comparator.comparingInt((Pair p) -> p.second).reversed());
Enter fullscreen mode Exit fullscreen mode

โœ… 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]));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ With objects:

PriorityQueue<Pair> pq = new PriorityQueue<>(Comparator.comparingInt(p -> p.second));
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 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));
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ Descending:

entries.sort(Comparator.comparingInt(Map.Entry::getValue).reversed());
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น 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());
Enter fullscreen mode Exit fullscreen mode

โ–ถ๏ธ TreeSet with custom objects:

TreeSet<Pair> set = new TreeSet<>(Comparator.comparingInt(p -> p.second));
Enter fullscreen mode Exit fullscreen mode

โš ๏ธ 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

  1. Use Comparator.comparingInt() for clean, readable sorting when dealing with objects.
  2. Use lambdas when working with primitive arrays or quick-and-dirty code.
  3. Always use .reversed() when sorting in descending order.
  4. For multiple sort keys (e.g., by value then key), use thenComparing():
   list.sort(Comparator.comparingInt((Pair p) -> p.second)
                       .thenComparingInt(p -> p.first));
Enter fullscreen mode Exit fullscreen mode

๐Ÿงพ 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)