How to sort objects with Comparable and Comparator in Java
Comparable
Comparator
sort
java
This tutorial will present how to order arrays and lists of primitive data and objects.
- primitive array sort
- primitive list sort
- object list sort using
java.lang.Comparable
- object list sort using
java.util.Comparator
.
1. Sort an Array
To sort an array of primitive data use Arrays.sort()
package com.admfactory.sort;
import java.util.Arrays;
public class SortArray {
public static void main(String[] args) {
System.out.println("Sort primitive array");
System.out.println();
int[] intArray = new int[] { 7, 6, 5, 4, 3, 2 };
System.out.print("Original: ");
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
Arrays.sort(intArray);
System.out.println();
System.out.print("Sorted: ");
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i] + " ");
}
}
}
Output
Sort primitive array
Original: 7 6 5 4 3 2
Sorted: 2 3 4 5 6 7
2. Sort a List
To sort a List of primitive data use Collections.sort()
package com.admfactory.sort;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortList {
public static void main(String[] args) {
System.out.println("Sort primitive list");
System.out.println();
List<String> list = new ArrayList<String>();
list.add("Tom");
list.add("Abel");
list.add("Peter");
list.add("John");
list.add("Lewis");
System.out.print("Original: ");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
Collections.sort(list);
System.out.println();
System.out.print("Sorted: ");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
}
Output
Sort primitive list
Original: Tom Abel Peter John Lewis
Sorted: Abel John Lewis Peter Tom
3. Sort objects with Comparable
First, we need to define what we want to sort. For this will take a simple example of users with a rating system in points and the sorting need to be done based on the points.
Here is the User class.
package com.admfactory.sort;
public class User implements Comparable<User> {
private String name;
private int points;
public User(String name, int points) {
this.name = name;
this.points = points;
}
public int getPoints() {
return this.points;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return name + " " + points;
}
@Override
public int compareTo(User per) {
if (this.points == per.points)
return 0;
else if (this.points > per.points)
return 1;
else
return -1;
}
}
The use the Comparable, the class need to implement Comparable interfaces and overwrite compareTo method. The compareTo method need to return int value:
- -1 - if the current object is smaller that the compare one
- 0 - if the objects are equal
- 1 - if the current object is bigger that the compare one
Usage
package com.admfactory.sort;
import java.util.Arrays;
public class SortComparable {
public static void main(String[] args) {
System.out.println("Sort array with comparable");
System.out.println();
User u1 = new User("User1", 12);
User u2 = new User("User2", 9);
User u3 = new User("User3", 32);
User u4 = new User("User4", 3);
User u5 = new User("User5", 1);
User[] users = new User[] { u1, u2, u3, u4, u5 };
System.out.println("Origial:");
for (int i = 0; i < users.length; i++) {
System.out.println(users[i]);
}
Arrays.sort(users);
System.out.println();
System.out.println("Sorted:");
for (int i = 0; i < users.length; i++) {
System.out.println(users[i]);
}
}
}
Output
Sort array with comparable
Origial:
User1 12
User2 9
User3 32
User4 3
User5 1
Sorted:
User5 1
User4 3
User2 9
User1 12
User3 32
4. Sort Objects with Comparator
The Comparable method allows you to sort using only one way. If you need the multiple criteria, you need to use Comparator and add for each sorting criteria one Comparator Class.
Here is the User class extended with tow Comparators.
package com.admfactory.sort;
import java.util.Comparator;
public class User implements Comparable<User> {
private String name;
private int points;
public User(String name, int points) {
this.name = name;
this.points = points;
}
public int getPoints() {
return this.points;
}
public String getName() {
return this.name;
}
@Override
public String toString() {
return name + " " + points;
}
@Override
public int compareTo(User per) {
if (this.points == per.points)
return 0;
else if (this.points > per.points)
return 1;
else
return -1;
}
public static Comparator<User> UserNameComparator = new Comparator<User>() {
public int compare(User user1, User user2) {
String userName1 = user1.getName().toUpperCase();
String userName2 = user2.getName().toUpperCase();
return userName1.compareTo(userName2);
}
};
public static Comparator<User> UserPointsComparator = new Comparator<User>() {
public int compare(User user1, User user2) {
int userPoints1 = user1.getPoints();
int userPoints2 = user2.getPoints();
if (userPoints1 == userPoints2)
return 0;
else if (userPoints1 > userPoints2)
return 1;
else
return -1;
}
};
}
The difference is that the class contains two new static members with inline implementation:
- UserNameComparator - will order based on name;
- UserPointsComparator - will order based on the points.
Usage
You can see the difference:
Arrays.sort(users);
vs
Arrays.sort(users, User.UserNameComparator);
If the Comparator parameter is missing the comparable method will be used.
package com.admfactory.sort;
import java.util.Arrays;
public class SortComparator {
public static void main(String[] args) {
System.out.println("Sort array with comparator");
System.out.println();
User u1 = new User("User1", 12);
User u2 = new User("User2", 9);
User u3 = new User("User3", 32);
User u4 = new User("User4", 3);
User u5 = new User("User5", 1);
User[] users = new User[] { u1, u2, u3, u4, u5 };
System.out.println("Origial:");
for (int i = 0; i < users.length; i++) {
System.out.println(users[i]);
}
Arrays.sort(users, User.UserPointsComparator);
System.out.println();
System.out.println("Sorted on points:");
for (int i = 0; i < users.length; i++) {
System.out.println(users[i]);
}
Arrays.sort(users, User.UserNameComparator);
System.out.println();
System.out.println("Sorted on name:");
for (int i = 0; i < users.length; i++) {
System.out.println(users[i]);
}
}
}
Output
Sort array with comparator
Origial:
User1 12
User2 9
User3 32
User4 3
User5 1
Sorted on points:
User5 1
User4 3
User2 9
User1 12
User3 32
Sorted on name:
User1 12
User2 9
User3 32
User4 3
User5 1