How To Sort Array In Java

7 min read

How to sort array in java is a fundamental skill for any developer working with collections of data. Whether you are building a simple utility, processing user input, or implementing complex algorithms, knowing the most efficient and readable ways to order elements can save time, reduce bugs, and improve application performance. This guide walks you through the built‑in Java mechanisms, custom ordering techniques, and practical tips for sorting both primitive and object arrays, while also highlighting performance considerations and common pitfalls to avoid That's the part that actually makes a difference. Nothing fancy..


Introduction

Sorting is the process of arranging items in a specific sequence—most commonly ascending or descending order—based on a comparable property such as numeric value, alphabetical order, or a custom rule. Here's the thing — in Java, arrays are fixed‑size containers that store elements of the same type, and the language provides several ready‑made utilities to sort them without reinventing the wheel. Here's the thing — the primary keyword how to sort array in java appears throughout this article to help search engines recognize the topic, while related terms like Arrays. sort, Comparator, stream sorting, and time complexity are woven in naturally to boost relevance Nothing fancy..


Understanding Arrays in Java

Before diving into sorting methods, it’s useful to recall what an array looks like in Java:

int[] numbers = {5, 2, 9, 1, 7};
String[] names = {"Alice", "Bob", "Charlie"};

Arrays are objects, but they differ from collections like ArrayList in that their size cannot change after creation. Because of this, sorting an array means rearranging the existing elements in‑place rather than creating a new container (although some approaches return a new view). The Java standard library offers three main pathways for sorting arrays:

  1. java.util.Arrays.sort() – works directly on primitive and object arrays.
  2. java.util.Collections.sort() – requires converting the array to a List.
  3. Java StreamsArrays.stream(...).sorted() returns a sorted stream that can be collected back into an array.

Each approach has its own advantages, which we will explore in detail.


Built‑in Sorting Methods

Using Arrays.sort()

The most straightforward way to sort an array is to call the static method Arrays.sort(). So it is overloaded for all primitive types (int, double, char, …) and for Object[] (or any subclass). For object arrays, the elements must implement Comparable, or you must supply a Comparator Turns out it matters..

import java.util.Arrays;

public class SortDemo {
    public static void main(String[] args) {
        int[] intArray = {4, 2, 8, 6};
        Arrays.out.sort(intArray); // sorts in ascending order
        System.println(Arrays.

        String[] strArray = {"banana", "apple", "cherry"};
        Arrays.sort(strArray); // uses String's natural ordering (lexicographic)
        System.out.println(Arrays.

**Key points**  
- The method sorts **in‑place**; the original array reference now points to the sorted data.  
- For primitives, it uses a tuned quicksort (dual‑pivot quicksort for Java 7+).  
- For objects, it uses a stable merge‑sort variant (TimSort) that guarantees O(n log n) worst‑case time and preserves the relative order of equal elements.

### Using `Collections.sort()` with a List  

If you prefer to work with the Collections framework, you can convert the array to a `List`, sort it, and then copy the result back:

```java
Integer[] integerArray = {5, 3, 9, 1};
List list = Arrays.asList(integerArray); // note: fixed‑size list backed by the array
Collections.sort(list); // sorts the list, which updates the original array
System.out.println(Arrays.toString(integerArray)); // [1, 3, 5, 9]

When to use this

  • You already have a List elsewhere in your code and want to reuse the same sorting logic.
  • You need additional List‑specific operations (e.g., subList, retainAll) before or after sorting.

Using Java Streams

Streams offer a functional‑style alternative that returns a new sorted sequence without mutating the source array:

double[] doubleArray = {2.5, 7.1, 3.3, 0.9};
double[] sorted = Arrays.stream(doubleArray)
                        .sorted()
                        .toArray();
System.out.println(Arrays.toString(sorted)); // [0.9, 2.5, 3.3, 7.1]

Advantages

  • Immutability: the original array stays unchanged, which can be safer in concurrent contexts.
  • Easy to chain with other stream operations (filter, map, limit, etc.).
  • Works naturally with primitive streams (IntStream, LongStream, DoubleStream).

Custom Comparator

When the natural ordering of elements does not suit your needs, you can supply a Comparator. This is especially useful for sorting objects by multiple fields or in a non‑alphabetical/numeric order.

class Person {
    String name;
    int age;
    Person(String n, int a) { name = n; age = a; }
    @Override public String toString() { return name + ":" + age; }
}

Person[] people = {
    new Person("Zoe", 25),
    new Person("Amy", 30),
    new Person("Bob", 20)
};

// Sort by age ascending, then by name if ages equal
Arrays.comparingInt((Person p) -> p.Consider this: age)
                              . sort(people, Comparator.thenComparing(p -> p.

System.out.println(Arrays.toString(people));
// Output: [Bob:20, Zoe:25, Amy:30]

Why a Comparator matters

  • Decouples ordering logic from the class definition (you can’t always modify Person to implement Comparable).
  • Enables multiple sorting strategies for the same type without creating wrapper classes.

Sorting Primitive vs Object Arrays

Aspect Primitive Arrays (int[], double[]) Object Arrays (String[], Person[])
Method Arrays.sort(primitiveArray) Arrays.sort(objectArray) or with Comparator
Underlying Algorithm Dual‑pivot quicksort (fast, in‑place) TimSort (stable, adaptive)
Null Handling

And yeah — that's actually more nuanced than it sounds.

Aspect Primitive Arrays (int[], double[]) Object Arrays (String[], Person[])
Method Arrays.nullsFirst(...sort(primitiveArray) Arrays.)).
Stability Not guaranteed (quicksort is unstable) Guaranteed stable (TimSort preserves order of equal elements). g., Comparator.sort(objectArray) or with Comparator
Underlying Algorithm Dual‑pivot quicksort (fast, in‑place) TimSort (stable, adaptive)
Null Handling Not applicable (primitives cannot be null) Throws NullPointerException if any element is null unless a null‑safe Comparator is provided (e.
Memory Overhead Minimal; sorts in place Requires temporary storage for merge phases (O(n) worst case).

Parallel Sorting for Large Datasets

When dealing with arrays that contain millions of elements, the parallel variants can make use of multiple CPU cores:

int[] large = new int[10_000_000];
// ... fill array ...
Arrays.parallelSort(large);               // primitives
Arrays.parallelSort(people, Comparator.comparingInt(p -> p.age)); // objects

When to prefer parallelSort

  • Array size exceeds a few hundred thousand elements.
  • The machine has multiple available cores and the workload is CPU‑bound.
  • You can tolerate the modest overhead of task splitting for smaller arrays (the JDK automatically falls back to sequential sort below a threshold).

Common Pitfalls & Best Practices

Pitfall Symptom Fix
Sorting a null array reference NullPointerException at runtime Guard with if (array !Still, = null) Arrays. sort(array);
Mutating a shared array unintentionally Bugs in concurrent code or unexpected side‑effects Use Arrays.stream(array).sorted().toArray() to produce a fresh copy, or copy first: Arrays.sort(array.clone()).
Assuming stability for primitives Equal keys change relative order Switch to an object wrapper (Integer[]) or implement a stable sort manually if stability is required.
Providing a Comparator that violates transitivity IllegalArgumentException or undefined order Ensure compare(a,b), compare(b,c), and compare(a,c) are consistent; prefer Comparator.comparing… builders. That said,
Boxing overhead in streams Slower performance for primitive streams Use IntStream, LongStream, DoubleStream directly (Arrays. stream(intArray) returns IntStream).

Performance Cheat‑Sheet

Operation Typical Complexity Notes
Arrays.sort(primitive[]) O(n log n) average, O(n²) worst (rare) Dual‑pivot quicksort; in‑place, cache‑friendly.
Arrays.sort(object[]) O(n log n) worst TimSort; stable, excels on partially sorted data.
Arrays.parallelSort(*) O(n log n) / p (p = cores) Overhead ~10‑20 % for small n; scales well beyond 10⁶ elements.
Stream sorted() O(n log n) + stream overhead Creates intermediate objects; prefer primitive streams for raw speed.

Conclusion

Java’s Arrays.sort family gives you a spectrum of tools—from the lightning‑fast, in‑place dual‑pivot quicksort for primitives to the stable, adaptive TimSort for objects, with functional stream variants and parallel overloads for modern multi‑core hardware. Choosing the right variant boils down to three questions:

  1. Mutability – Do you need to keep the original array intact? Use streams or copy first.
  2. Data type – Primitives get quicksort; objects get TimSort (and stability).
  3. Scale – For large datasets on multi‑core machines, parallelSort often delivers the best throughput.

By pairing the appropriate sorting method with a well‑crafted Comparator (or the natural Comparable contract), you gain predictable, maintainable, and performant ordering logic that integrates cleanly into both imperative and functional code paths. Master these options, and array sorting ceases to be a bottleneck—it becomes a reliable building block in your Java toolkit.

Just Added

New on the Blog

Round It Out

Related Posts

Thank you for reading about How To Sort Array In Java. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home