Interview Kickstart has enabled over 21000 engineers to uplevel.
Collections sort in Java provides in-built methods to sort data faster and in an easier manner. Many software engineering interviews require sorting of a list or an array; implementing a sorting algorithm from scratch in an interview can be cumbersome. For some problems, the sorting part of the task can be simplified using the abilities of Java Collections. In this article, we will cover Collections sort in Java in detail:
Collections sort is a method of Java Collections class used to sort a list, which implements the List interface. All the elements in the list must be mutually comparable. If a list consists of string elements, then it will be sorted in alphabetical order. If it consists of a date element, it will be sorted into chronological order.
How does it happen? String and date both implement the Comparable interface in Java. Comparable implementations provide a natural ordering for a class, which allows the object of that class to be sorted properly.
ClassCastException: If the list contains elements that are not mutually comparable using the specified comparator, it will throw ClassCastException.
The sort is guaranteed to be stable, i.e., the order of equal elements after performing sort will remain unchanged. By default, this method sorts the list in ascending order of elements. Collections.sort is used to sort all data structures such as linkedList, ArrayList, and queue.
The Collections.sort has two overloaded methods :
Let’s take an example to sort the list of elements in ascending order. We have a list of student names, and we’ll sort them in ascending order.
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> studentName = Arrays.asList("Tom","John","Harry","Philip","Max");
Collections.sort(studentName);
for(String name : studentName) {
System.out.println(name);
}
}
}
Output:
By default, Collections.sort will sort the names in alphabetical order. We can also sort the student names in descending order using Collections.reverseOrder().
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> studentName = Arrays.asList("Tom","John","Harry","Philip","Max");
Collections.sort(studentName, Collections.reverseOrder());
for(String name : studentName) {
System.out.println(name);
}
}
}
Output:
Sorting in descending order can be done using a comparator too. Let’s have a look at the code below.
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> studentName = Arrays.asList("Tom","John","Harry","Philip","Max");
Collections.sort(studentName, new Comparator<String>(){
public int compare(String a, String b) {
return b.compareTo(a);
}
});
for(String name : studentName) {
System.out.println(name);
}
}
}
This can also be done using lambda expressions:
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> studentName = Arrays.asList("Tom","John","Harry","Philip","Max");
Collections.sort(studentName, (a, b)-> b.compareTo(a));
studentName.forEach((name)->System.out.println(name));
}
}
Let’s take an example to understand comparator-based sorting. We have a list of student details, and we want to sort them based on their total marks.
Student details: Name, mathScore, physicsScore, chemistryScore
We have all the scores obtained by the students in each subject. We want to sort the list of the students based on their total marks (mathScore + physicsScore + chemistryScore). Let’s assume that two students' total marks can’t be equal in this case.
import java.util.*;
class Student {
String name;
int mathMarks;
int physicsMarks;
int chemistryMarks;
Student(String name, int mathMarks, int physicsMarks, int chemistryMarks) {
this.name = name;
this.mathMarks = mathMarks;
this.physicsMarks = physicsMarks;
this.chemistryMarks = chemistryMarks;
}
@Override
public String toString(){
return this.name + " " + this.mathMarks + " " + this.physicsMarks + " " + this.chemistryMarks;
}
public int totalMarks() {
return this.mathMarks + this.physicsMarks + this.chemistryMarks;
}
public static void main(String [] args) {
List<Student> listOfStudents = new ArrayList<>();
listOfStudents.add(new Student("John", 70, 50, 80));
listOfStudents.add(new Student("Tom", 40, 50, 60));
listOfStudents.add(new Student("Harry", 90, 50, 40));
listOfStudents.add(new Student("Max", 80, 90, 40));
listOfStudents.add(new Student("Philip", 60, 70, 90));
// sort using lambda supported by java 8 and above
Collections.sort(listOfStudents, new Comparator<Student>() {
public int compare(Student student1, Student student2) {
return student1.totalMarks() - student2.totalMarks();
}
});
for(Student student: listOfStudents) {
System.out.println(student.toString());
}
}
}
Output:
We can also use lambda expressions here. Let’s have a look at the code below.
import java.util.*;
class Student {
String name;
int mathMarks;
int physicsMarks;
int chemistryMarks;
Student(String name, int mathMarks, int physicsMarks, int chemistryMarks) {
this.name = name;
this.mathMarks = mathMarks;
this.physicsMarks = physicsMarks;
this.chemistryMarks = chemistryMarks;
}
@Override
public String toString(){
return this.name + " " + this.mathMarks + " " + this.physicsMarks + " " + this.chemistryMarks;
}
public int totalMarks() {
return this.mathMarks + this.physicsMarks + this.chemistryMarks;
}
public static void main(String [] args) {
List<Student> listOfStudents = new ArrayList<>();
listOfStudents.add(new Student("John", 70, 50, 80));
listOfStudents.add(new Student("Tom", 40, 50, 60));
listOfStudents.add(new Student("Harry", 90, 50, 40));
listOfStudents.add(new Student("Max", 80, 90, 40));
listOfStudents.add(new Student("Philip", 60, 70, 90));
// sort using lambda supported by java 8 and above
Collections.sort(listOfStudents, (student1, student2) -> student1.totalMarks() - student2.totalMarks());
listOfStudents.forEach((student)-> System.out.println(student.toString()));
}
}
The sort method transfers control to the compare method, and compare method returns values based on the arguments passed:
Based on the values returned, the function decides whether to swap the values.
For more tech interview questions and problems, check out the following pages: Interview Questions and Problems
Question 1: What is the difference between Arrays.sort() vs. Collections.sort()?
Answer: Collections.sort operates on a list, while Arrays.sort operates on an array. Arrays.sort() and Collections.sort() use two different algorithms. Internally, Collections.sort converts the input list into an array and calls Arrays.sort to sort the resulting array.
Question 2: Can we use Collections.sort to sort a 2-dimensional array?
Answer: Yes. We can use Collections to sort a 2-dimensional array. Following is an example, where we sort the given 2D array based on the first element:
import java.util.*;
class Main {
public static void main(String[] args) {
int[][] array = {
{3, 10},{18, 1}
};
Arrays.sort(array, new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2) {
return Integer.compare(o1[0],o2[0]);
}
});
for(int i = 0; i< array.length; i++) {
for(int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]+" ");
}System.out.println();
}
}
}
In the example, we have sorted each array[i] based on the first values present in them as there is no default way to sort an array of arrays.
Question 3: Can we sort a sublist using Collections.sort()?
Answer: No. Collections.sort() doesn’t provide any built-in method to sort the sublist, but we can sort a subarray using Arrays.sort(). We can pass the fromIndex and toIndex along with the array. Let’s see an example:
import java.util.Arrays;
import java.util.Comparator;
class Main {
public static void main(String[] args) {
Integer array[] = { 1 , 5 , 3, 4 , 2 , 7 , 6 };
Arrays.sort(array, 1 , 5 , new Comparator<Integer>(){
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1,o2);
}
});
for(int i = 0; i< array.length; i++) {
System.out.print(array[i]+" ");
}
}
}
Output: 1 2 3 4 5 7 6
As evident from the sample output, we sorted the range [fromIndex, endIndex). Here, fromIndex is included, and endIndex is excluded.
Also, since the array is 0-indexed, we sorted the range [1, 5), where index 1 is included, and index 5 is excluded.
If you’re looking for guidance and help to nail your next technical interview, sign up for our free webinar. As pioneers in the field of technical interview prep, we have trained thousands of software engineers to crack the toughest coding interviews and land their dream jobs at Google, Facebook, Apple, Netflix, Amazon, and other Tier-1 tech companies.
Join our webinar to learn more!
Check out our learn page for more articles on Java:
----------
Article contributed Problem Setters Official
Attend our webinar on
"How to nail your next tech interview" and learn