Lesson 6

Mastering Java's Built-in Sorting Functions: Arrays and Collections

Lesson Introduction and Overview

Hello, and welcome back! Our journey today takes us into the sorting universe in Java. We will learn about and use two built-in sorting functions: Arrays.sort() and Collections.sort(). These ready-to-use tools in Java simplify the task of sorting significantly. Let's get started!

Understanding Sorting and Its Importance

Sorting refers to arranging data in a specific order, which enhances the efficiency of search or merge operations on data. In real life, we sort books alphabetically or clothes by size. Similar concepts are applicable in programming, where sorting large lists of data for more effective analysis is a frequent practice.

An Introduction to Java's Built-in Sorting Functions

Java offers a built-in sorting method Arrays.sort() to sort arrays. Here's a demonstration of how we use this method:

Sorting of Primitive Types and Objects

Sorting with Arrays.sort() makes sorting arrays of primitives a breeze. Let's see it in action!

Sorting Arrays of Primitives

1int[] arr = {4, 1, 3, 2}; 2Arrays.sort(arr); 3System.out.println(Arrays.toString(arr)); // Output: [1, 2, 3, 4]

Sorting Arrays of Objects

1String[] inventory = {"Bananas", "Pears", "Apples", "Dates"}; 2Arrays.sort(inventory); 3for (String item : inventory) { 4 System.out.println(item); 5}

As you can see, sorting in Java is as simple as that!

More Complex Sorting Problem

Java's Comparator interface enables us to dictate the sorting order by setting custom rules. Let's sort a list of students by their grades, with alphabetical sorting applied in the event of ties-in grades. Firstly, we define the Student class:

1class Student { 2 String name; 3 int grade; 4 5 Student(String name, int grade) { 6 this.name = name; 7 this.grade = grade; 8 } 9 10 public int getGrade() {return this.grade;} 11 public String getName() {return this.name;} 12 public String toString() { 13 return name + ":" + grade; 14 } 15}

Note that it has to have getters for its fields for the Comparator to work.

Custom Sorting with Comparator

Modern Java makes solving such sorting tasks straightforward. Here is how we do it using the Comparator interface:

1class Solution { 2 3 public static void main(String[] args) { 4 ArrayList<Student> students = new ArrayList<>( 5 Arrays.asList( 6 new Student("Alice", 85), 7 new Student("Bob", 90), 8 new Student("Charlie", 90) 9 ) 10 ); 11 12 students.sort(Comparator.comparing(Student::getGrade).reversed().thenComparing(Student::getName)); 13 14 System.out.println(students); // Output: [Alice:90, Bob:85, Charlie:85] 15 } 16}

In the above example, we create an ArrayList of Student objects and sort it using a custom Comparator. The Comparator.comparing(Student::getGrade).reversed() portion first creates a Comparator that compares Student objects based on their grades, and reversed() is used to reverse the natural ordering of the Comparator, thus ensuring that Students with higher grades come first.

If two students have the same grade, thenComparing(Student::getName) then compares the students based on their names in alphabetical order.

Applying Reverse Order to thenComparing

There is a small problem with the reversed() method. Imagine a situation where we want to sort students in ascending order by their grades but in descending order alphabetically. In this case, our previous tools won't work as expected:

1students.sort(Comparator.comparing(Student::getGrade).thenComparing(Student::getName).reversed()); 2// Result: [Charlie:90, Bob:90, Alice:85]

The .reversed() method reverses the sorted array, making both grades and names in descending order. To tackle this problem, we can pass the Comparator.reverseOrder() functions as the second parameter of the .thenComparing() function:

1students.sort(Comparator.comparing(Student::getGrade).thenComparing(Student::getName, Comparator.reverseOrder())); 2// [Alice:85, Charlie:90, Bob:90]

This way, only the names sorting gets reversed.

Lesson Summary and Next Steps

Well done! You've learned how sorting functions in Java and have used Java's built-in sorting functions.

In our future lessons, we'll delve deeper into sorting and tackling more intricate problems, such as finding the K-th largest number. So, stay tuned and get ready to sort your way to success! Happy coding!

Enjoy this lesson? Now it's time to practice with Cosmo!

Practice is how you turn knowledge into actual skills.