Java
Array Sorting
Comparator
Parallel Arrays
Programming Tutorial

Java - Sort one array based on values of another array?

Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms

Introduction

When two arrays are related by position, sorting one of them usually means you must reorder the other one in exactly the same way. Java does not provide a direct API for sorting parallel arrays together, so the usual solution is to sort indices or temporary pairs and then rebuild the arrays in the new order.

Sort by Building an Index Order

Suppose you have names and scores, and you want the names ordered by the score array. One safe approach is to sort an array of indices based on the values in the key array.

java
1import java.util.Arrays;
2import java.util.Comparator;
3import java.util.stream.IntStream;
4
5public class ParallelArraySort {
6    public static void main(String[] args) {
7        String[] names = {"api", "worker", "web", "cron"};
8        int[] priorities = {30, 10, 20, 40};
9
10        Integer[] order = IntStream.range(0, priorities.length)
11                .boxed()
12                .toArray(Integer[]::new);
13
14        Arrays.sort(order, Comparator.comparingInt(i -> priorities[i]));
15
16        String[] sortedNames = new String[names.length];
17        int[] sortedPriorities = new int[priorities.length];
18
19        for (int i = 0; i < order.length; i++) {
20            int originalIndex = order[i];
21            sortedNames[i] = names[originalIndex];
22            sortedPriorities[i] = priorities[originalIndex];
23        }
24
25        System.out.println(Arrays.toString(sortedNames));
26        System.out.println(Arrays.toString(sortedPriorities));
27    }
28}

This keeps the relationship intact because the index order is computed once and then applied to both arrays. It also works well when the value array is primitive, since Java cannot sort a primitive array with a custom comparator directly.

Sorting in Descending Order or by Multiple Keys

You can adjust the comparator without changing the pattern. For descending order, reverse the comparison. If you have a secondary key, include it in the comparator so ties are predictable.

java
1Arrays.sort(order, (left, right) -> {
2    int byPriority = Integer.compare(priorities[right], priorities[left]);
3    if (byPriority != 0) {
4        return byPriority;
5    }
6
7    return names[left].compareTo(names[right]);
8});

This is often better than trying to keep two arrays synchronized while swapping elements manually inside a custom sort loop.

Using a Pair Object Instead

If you control the data model, a better design is often to stop using parallel arrays at all. Wrap related values in one object and sort a single array or list of those objects.

java
1import java.util.Arrays;
2
3record Job(String name, int priority) {}
4
5Job[] jobs = {
6    new Job("api", 30),
7    new Job("worker", 10),
8    new Job("web", 20)
9};
10
11Arrays.sort(jobs, java.util.Comparator.comparingInt(Job::priority));

This version is easier to read and harder to break because the relationship between the values is encoded in the type rather than in matching indexes.

When Parallel Arrays Still Make Sense

Parallel arrays can still be fine in performance-sensitive code, low-level data processing, or legacy codebases where changing the structure is expensive. In those cases, sorting indices is usually the cleanest compromise between speed and clarity.

If you need the sort to mutate the original arrays in place, copy the sorted results back into the originals after computing the order. That keeps the algorithm simple and reduces swap-related bugs.

Common Pitfalls

The most common bug is forgetting to reorder both arrays. If you sort only the key array and leave the value array untouched, the positional relationship is destroyed immediately.

Another mistake is assuming both arrays always have the same length. Validate that assumption before sorting, because a mismatch means the data is already inconsistent.

Be careful with duplicate keys. If many items have the same key value, define whether the original order should be preserved or whether a secondary comparison rule should decide the order.

Finally, if you find yourself repeating this pattern often, it is usually a sign that a small class or record would be a better representation than two separate arrays.

Summary

  • To sort one Java array by another, sort indices or temporary pairs.
  • Index sorting works especially well when the key array is primitive.
  • Reapply the computed order to every related array so positions stay aligned.
  • Add secondary comparisons when duplicate keys need deterministic ordering.
  • Prefer a small object or record instead of parallel arrays when you can change the model.

Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms