0Pricing
Java Academy · Lesson

Sorting Arrays and Collections in Practice

Apply sorting to product lists, leaderboards, and event schedules using real-world examples.

Sorting Arrays and Collections in Practice is a free Java Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Java Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Sorting in Practice

This lesson applies sorting techniques to realistic scenarios: product catalogs, leaderboards, event scheduling, and search result ranking.

Arrays.sort for Primitive Arrays

Arrays.sort() for primitive arrays uses a dual-pivot quicksort — extremely fast, O(n log n) average.

int[] scores = {45, 90, 78, 62, 88, 33};
Arrays.sort(scores);
System.out.println(Arrays.toString(scores)); // [33, 45, 62, 78, 88, 90]

// Sort a range only
int[] data = {9, 3, 7, 1, 5};
Arrays.sort(data, 1, 4); // sort indices 1-3 only
System.out.println(Arrays.toString(data)); // [9, 1, 3, 7, 5]

Arrays.sort for Object Arrays

For object arrays, Arrays.sort() uses TimSort (stable). You can provide a Comparator for custom ordering.

String[] names = {"Charlie", "Alice", "Bob", "Diana"};
Arrays.sort(names);
System.out.println(Arrays.toString(names)); // [Alice, Bob, Charlie, Diana]

// Custom order: by length, then alphabetically
Arrays.sort(names, Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()));
System.out.println(Arrays.toString(names)); // [Bob, Alice, Diana, Charlie]

Collections.sort and List.sort

Both sort List in place. List.sort() is the modern preferred way.

List<Integer> nums = new ArrayList<>(List.of(5, 2, 8, 1, 9, 3));

// Old way
Collections.sort(nums);
System.out.println(nums); // [1, 2, 3, 5, 8, 9]

// Modern way (same result)
nums.sort(Comparator.naturalOrder());
nums.sort(null); // null means natural order

// Descending
nums.sort(Comparator.reverseOrder());
System.out.println(nums); // [9, 8, 5, 3, 2, 1]

Stream.sorted() for Functional Style

Use stream().sorted() when building a pipeline — produces a new sorted stream without modifying the source.

List<String> cities = List.of("Tokyo", "London", "New York", "Paris", "Sydney");

// Sorted stream — source list unchanged
List<String> sorted = cities.stream()
    .sorted(Comparator.comparingInt(String::length).thenComparing(Comparator.naturalOrder()))
    .collect(Collectors.toList());

System.out.println(sorted);
// [Paris, Tokyo, London, Sydney, New York]

Sorting a Map by Value

A classic interview question: sort a Map by its values using stream and Comparator.

import java.util.*;
import java.util.stream.*;

Map<String, Integer> scores = Map.of(
    "Alice", 95, "Bob", 87, "Charlie", 92, "Diana", 87
);

Map<String, Integer> sorted = scores.entrySet().stream()
    .sorted(Map.Entry.<String, Integer>comparingByValue(Comparator.reverseOrder())
        .thenComparing(Map.Entry.comparingByKey()))
    .collect(Collectors.toLinkedHashMap(
        Map.Entry::getKey, Map.Entry::getValue,
        (v1, v2) -> v1, LinkedHashMap::new));

sorted.forEach((k, v) -> System.out.println(k + ": " + v));
// Alice: 95 / Charlie: 92 / Bob: 87 / Diana: 87

Sorting with Collator for Locale

For language-aware string sorting, use java.text.Collator instead of String.compareTo — it handles accents, case, and locale-specific ordering.

import java.text.*;
import java.util.*;

List<String> names = new ArrayList<>(List.of("éclair", "apple", "Über", "banana"));

Collator collator = Collator.getInstance(Locale.GERMAN);
names.sort(collator);
System.out.println(names); // locale-aware sort

Sorting Objects with Multiple Criteria

E-commerce product sort: in-stock first, then by sale price, then by rating, then by name.

record Product(String name, double price, double salePrice, double rating, boolean inStock) {}

Comparator<Product> bestFirst = Comparator
    .comparing(Product::inStock).reversed()           // in-stock first
    .thenComparingDouble(Product::salePrice)          // cheapest sale price
    .thenComparingDouble(Product::rating).reversed()  // highest rated
    .thenComparing(Product::name);                    // alphabetical tiebreak

Sorting Events by Date and Time

Sorting a schedule of events chronologically using java.time types which implement Comparable.

import java.time.*;
import java.util.*;

record Event(String title, LocalDate date, LocalTime time) {}

List<Event> schedule = new ArrayList<>(List.of(
    new Event("Workshop",  LocalDate.of(2024,7,15), LocalTime.of(9, 0)),
    new Event("Keynote",   LocalDate.of(2024,7,14), LocalTime.of(10, 30)),
    new Event("Lunch Talk",LocalDate.of(2024,7,15), LocalTime.of(12, 0)),
    new Event("Hackathon", LocalDate.of(2024,7,14), LocalTime.of(9, 0))
));

schedule.sort(Comparator.comparing(Event::date).thenComparing(Event::time));
schedule.forEach(e -> System.out.println(e.date() + " " + e.time() + " " + e.title()));

Top-N Elements with Sorting

Finding the top-N elements efficiently: sort descending and take the first N, or use a PriorityQueue for large datasets.

List<Integer> values = List.of(42, 17, 88, 5, 73, 56, 91, 33);

// Simple approach: sort descending, take first 3
List<Integer> top3 = values.stream()
    .sorted(Comparator.reverseOrder())
    .limit(3)
    .collect(Collectors.toList());
System.out.println(top3); // [91, 88, 73]

// For very large datasets: PriorityQueue min-heap approach is O(n log k)
import java.util.PriorityQueue;
PriorityQueue<Integer> heap = new PriorityQueue<>(3);
for (int v : values) {
    heap.offer(v);
    if (heap.size() > 3) heap.poll();
}
System.out.println(new TreeSet<>(heap).descendingSet()); // [73, 88, 91]

Deduplication with Sorting

After sorting, duplicates are adjacent — O(n) detection is possible.

int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5};
Arrays.sort(arr); // sort first

// Remove duplicates in O(n) after sorting
int[] unique = Arrays.stream(arr).distinct().toArray();
System.out.println(Arrays.toString(unique)); // [1, 2, 3, 4, 5, 6, 9]

Performance: Choosing the Sort Method

Choosing the right sort approach:

  • Primitive arrays: Arrays.sort() — fastest, in-place quicksort
  • Object arrays/lists with Comparable: Collections.sort() or List.sort(null)
  • Multiple orderings: Comparator chains with thenComparing
  • Top-N from large stream: PriorityQueue or Stream.sorted().limit(N)

Quick Check

What sorting algorithm does Java use for object arrays in Arrays.sort()?

Recap: Sorting Arrays and Collections in Practice

Key takeaways:

  • Arrays.sort() for primitives uses dual-pivot quicksort; for objects uses TimSort (stable)
  • List.sort(comparator) and Collections.sort() are both stable TimSort
  • stream().sorted() produces a new sorted stream without modifying the source
  • Sort Map by value: entrySet().stream().sorted(Map.Entry.comparingByValue())
  • Use Collator for locale-aware string sorting
  • For top-N from large data: PriorityQueue with capacity k is more efficient than full sort

Frequently asked questions

Is the “Sorting Arrays and Collections in Practice” lesson free?

Yes — the full text of “Sorting Arrays and Collections in Practice” is free to read here on the web, and the Java Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Java Academy course, upgrade to CoddyKit PRO.

What will I learn in “Sorting Arrays and Collections in Practice”?

Apply sorting to product lists, leaderboards, and event schedules using real-world examples. You practise Java Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Java Academy?

No prior experience is required. Java Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Sorting Arrays and Collections in Practice” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Java Academy lesson?

Yes. Every Java Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Comparable Interface
  2. Comparator and Lambda Sorting
  3. Multi-Key Sorting with thenComparing
  4. Sorting Arrays and Collections in Practice
← Back to Java Academy