Sorting an array of objects in Java is a common requirement for any programmer. Sorting can be done based on different parameters like name, age, salary, and so on. Java provides different sorting techniques from which we can choose according to our needs.
In this article, we will discuss the different methods to sort an array of objects in Java. We will also provide practical examples to clarify the concepts.
Sorting an array of objects with Comparable interface
The Comparable interface is used when we want to sort an array of objects using their natural ordering. The natural ordering is determined by the compareTo() method, which is defined in the Comparable interface. To use this method, we need to implement the Comparable interface in our class and define the compareTo() method. Let's take an example to understand this.
Example:
Suppose we have a Person class, which has three properties: name, age, and salary. We want to sort an array of Person objects based on their age. To do so, we need to implement the Comparable interface in our Person class and define the compareTo() method based on age.
class Person implements Comparable<Person>{
String name;
int age;
double salary;
public int compareTo(Person p){
return this.age - p.age;
}
}
In the above example, we have implemented the Comparable interface in our Person class and defined the compareTo() method, which compares two Person objects based on their age. Now we can use the Arrays.sort() method to sort an array of Person objects based on their age.
Example:
public static void main(String[] args) {
Person[] persons = new Person[3];
persons[0] = new Person("John", 25, 5000);
persons[1] = new Person("Mike", 45, 7000);
persons[2] = new Person("David", 30, 6000);
Arrays.sort(persons);
for(Person p:persons)
System.out.println(p.name+" "+p.age+" "+p.salary);
}
Output:
John 25 5000.0
David 30 6000.0
Mike 45 7000.0
In the above example, we have defined an array of Person objects and used the Arrays.sort() method to sort them based on their age. The output shows that the array is sorted in ascending order based on age.
Sorting an array of objects with Comparator interface
The Comparator interface is used when we want to sort an array of objects based on a different parameter than their natural ordering. The Comparator interface provides two methods: compare() and equals(). We need to implement the compare() method to compare two objects based on our required parameter. Let's take an example to understand this.
Example:
Suppose we have a Person class, which has three properties: name, age, and salary. We want to sort an array of Person objects based on their salary. To do so, we need to implement the Comparator interface in our class and define the compare() method based on salary.
class SalaryComparator implements Comparator<Person>{
public int compare(Person p1, Person p2){
return (int)(p2.salary - p1.salary);
}
}
In the above example, we have defined a SalaryComparator class, which implements the Comparator interface and defines the compare() method. The compare() method compares two Person objects based on their salary.
Now, we can pass an object of the SalaryComparator class to the Arrays.sort() method to sort an array of Person objects based on their salary.
Example:
public static void main(String[] args) {
Person[] persons = new Person[3];
persons[0] = new Person("John", 25, 5000);
persons[1] = new Person("Mike", 45, 7000);
persons[2] = new Person("David", 30, 6000);
Arrays.sort(persons, new SalaryComparator());
for(Person p:persons)
System.out.println(p.name+" "+p.age+" "+p.salary);
}
Output:
Mike 45 7000.0
David 30 6000.0
John 25 5000.0
In the above example, we have defined an array of Person objects and used the Arrays.sort() method with an object of SalaryComparator class to sort them based on salary. The output shows that the array is sorted in descending order based on salary.
Conclusion
Sorting an array of objects in Java is a necessary requirement in many programming scenarios. Java provides different techniques, such as Comparable and Comparator interfaces, to sort an array of objects based on our needs. We have discussed these techniques with practical examples to clarify the concepts. It is essential to understand these techniques to efficiently sort an array of objects in Java.
let's dive a bit deeper into the previous topics.
Comparable interface
The Comparable interface is used for defining the natural ordering of a class's objects. When we implement the Comparable interface in a class, we need to implement the compareTo() method that compares the current object with the specified object. The compareTo() method returns a negative integer, zero, or a positive integer as the current object is less than, equal to, or greater than the specified object, respectively.
It's important to note that if we try to sort an array of objects that do not implement the Comparable interface, we'll receive a ClassCastException at runtime.
For example, let's say we have a class Book with the properties title, author, and price. We want to sort an array of Book objects based on their price, so we need to implement the Comparable interface in our Book class and define the compareTo() method based on the price.
public class Book implements Comparable<Book> {
private String title;
private String author;
private double price;
// constructor, getters and setters
@Override
public int compareTo(Book book) {
return Double.compare(this.price, book.price);
}
}
In the above example, we have implemented the Comparable interface in our Book class and defined the compareTo() method based on the price. The Double.compare() method is used to compare the prices of two books because we are dealing with double values.
Comparator interface
The Comparator interface is used for defining a specific way of comparing objects for sorting purposes. Unlike Comparable, we don't need to modify the original class because the Comparator interface has a separate implementation to define the way we compare objects.
When we implement the Comparator interface, we need to implement the compare() method to compare two objects. The compare() method returns a negative integer, zero, or a positive integer if the first object is less than, equal to, or greater than the second object, respectively.
For example, let's say we have the same Book class as before, and we want to sort the Book objects based on their title's length. So instead of modifying the Book class, we can create a new class called TitleLengthComparator that implements the Comparator interface and defines the compare() method based on the title length.
public class TitleLengthComparator implements Comparator<Book> {
@Override
public int compare(Book book1, Book book2) {
return Integer.compare(book1.getTitle().length(), book2.getTitle().length());
}
}
In the above example, we have defined a new class called TitleLengthComparator that implements the Comparator interface and defines the compare() method based on the title length. The Integer.compare() method is used to compare the length of the titles as we are dealing with integer values.
We can then use the Arrays.sort() method with an instance of the TitleLengthComparator class to sort the Book objects based on their title's length.
Book[] books = new Book[] {
new Book("The Catcher in the Rye", "J.D. Salinger", 12.99),
new Book("To Kill a Mockingbird", "Harper Lee", 10.99),
new Book("1984", "George Orwell", 9.99)
};
Arrays.sort(books, new TitleLengthComparator());
for (Book book : books) {
System.out.println(book.getTitle() + " - " + book.getPrice());
}
Output:
1984 - 9.99
To Kill a Mockingbird - 10.99
The Catcher in the Rye - 12.99
Conclusion
Sorting an array of objects is a crucial operation in programming, and Java provides tools to make it easy for us. The Comparable interface and Comparator interface are two different ways we can sort an array of objects based on our requirements. By understanding how these interfaces work and implementing them in our classes, we can easily sort arrays of objects to fit our needs.
Popular questions
- What is the Comparable interface used for in Java?
The Comparable interface is used for defining the natural ordering of a class's objects. It has a compareTo() method that compares the current object with the specified object. When we implement the Comparable interface in a class, we need to define the compareTo() method based on the class's natural ordering.
- What is the Comparator interface used for in Java?
The Comparator interface is used for defining a specific way of comparing objects for sorting purposes. It also has a compare() method to compare two objects. When we implement the Comparator interface, we need to define the compare() method based on a specific ordering of objects. We can use Comparator interface for sorting objects based on multiple criteria.
- What happens if we try to sort an array of objects that do not implement the Comparable interface?
If we try to sort an array of objects that do not implement the Comparable interface, we'll receive a ClassCastException at runtime.
- How do we sort an array of objects based on multiple criteria in Java?
We can use the Comparator interface to sort an array of objects based on multiple criteria. We need to define multiple comparators and then use them in the Arrays.sort() method's overloaded version that takes a Comparator object as a parameter.
- Can we use lambdas for defining the ordering of objects in Java?
Yes, we can use lambdas for defining the ordering of objects in Java. Lambdas provide a concise way of defining the compare() method without implementing the Comparator interface. We can use the Comparator's comparing() method to create a new Comparator object using a lambda expression.
Tag
Sortation