How to sort an ArrayList of objects in Java:
In this post, I will show you how to sort an ArrayList of objects in Java in different ways. I will try to keep the tutorial simple with a small number of sample objects. We will learn to sort an ArrayList of objects by comparing one single field or multiple fields.
Java program to use in the examples:
The following program will be used in the below examples:
Create a file Car.java:
public class Car {
int id;
String color;
public int getId() {
return id;
}
public String getColor() {
return color;
}
public Car(int id, String color) {
this.id = id;
this.color = color;
}
@Override
public String toString() {
return "id: " + id + ", color: " + color;
}
}
And the Main class as below:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<Car> cars = new ArrayList<>();
cars.add(new Car(1, "Red"));
cars.add(new Car(5, "Blue"));
cars.add(new Car(4, "Green"));
cars.add(new Car(3, "Raspberry"));
cars.add(new Car(2, "Gamboge"));
for (Car car : cars) {
System.out.println(car);
}
}
}
- In this example, we created one class Car to hold the information of a car, one integer id and one String color.
- We created an ArrayList car and inserted five Car objects to the ArrayList. The for loop prints the content of the ArrayList.
If you run this program, it will print the below output:
id: 1, color: Red
id: 5, color: Blue
id: 4, color: Green
id: 3, color: Raspberry
id: 2, color: Gamboge
We will use this program in the below examples to sort the array.
Method 1: By using Collections.sort() and Comparator.comparing():
We can use the Collections.sort() method to sort the ArrayList. The first parameter is the ArrayList to sort and the second parameter is a Comparator object that defines the order of the list.
The following code snippet will sort the elements by their ids:
Collections.sort(cars, Comparator.comparingInt(Car::getId));
for (Car car : cars) {
System.out.println(car);
}
We have passed Comparator.comparingInt method as the comparator to this method. It will sort the items by their ids:
id: 1, color: Red
id: 2, color: Gamboge
id: 3, color: Raspberry
id: 4, color: Green
id: 5, color: Blue
If you want to compare the elements by their names, you can write as below:
Collections.sort(cars, Comparator.comparing(Car::getColor));
for (Car car : cars) {
System.out.println(car);
}
It will sort the items by their names:
id: 5, color: Blue
id: 2, color: Gamboge
id: 4, color: Green
id: 3, color: Raspberry
id: 1, color: Red
Method 2: By using List.sort():
We can also use the List.sort() method instead of Collections.sort. This method takes one Comparator object and sorts the items of the ArrayList.
cars.sort(Comparator.comparing(Car::getColor));
for (Car car : cars) {
System.out.println(car);
}
It will sort the items by their names.
Method 3: By using stream:
We can convert the ArrayList to a stream, sort the items and convert the stream back to ArrayList.
ArrayList<Car> sortedCars = (ArrayList<Car>)cars.stream()
.sorted(Comparator.comparing(Car::getColor))
.collect(Collectors.toList());
for (Car car : sortedCars) {
System.out.println(car);
}
This example is sorting the items by their names.
id: 5, color: Blue
id: 2, color: Gamboge
id: 4, color: Green
id: 3, color: Raspberry
id: 1, color: Red
Method 4: Sort by multiple properties:
We can add more comparison conditions to the Comparator object. For example:
ArrayList<Car> cars = new ArrayList<>();
cars.add(new Car(1, "Red"));
cars.add(new Car(5, "Blue"));
cars.add(new Car(5, "Green"));
cars.add(new Car(1, "Raspberry"));
cars.add(new Car(2, "Gamboge"));
cars.sort(Comparator.comparing(Car::getId).thenComparing(Car::getColor));
for (Car car : cars) {
System.out.println(car);
}
This will sort the items by comparing the ids of the objects, and then it will compare the colors of the objects. For example, if two items have similar ids, the sort will be based on the color.
The above program will print the below result:
id: 1, color: Raspberry
id: 1, color: Red
id: 2, color: Gamboge
id: 5, color: Blue
id: 5, color: Green
Note that you can also use this method with stream sorted() method as explained in the previous example.
Method 5: How to sort the items in reverse:
You can use the reversed() method of the Comparator class to do a reverse sorting:
cars.sort(Comparator.comparing(Car::getId).thenComparing(Car::getColor).reversed());
for (Car car : cars) {
System.out.println(car);
}
It will print:
id: 5, color: Green
id: 5, color: Blue
id: 2, color: Gamboge
id: 1, color: Red
id: 1, color: Raspberry
Method 6: How to use a custom comparator:
We can create a custom comparator class to write our own comparison logic.
- Create one class that implements the Comparator interface
- Override the compare method that takes two objects as its parameters and returns one integer value.
- Return zero if both objects are equal.
- Return a negative value if the first object is less than the second object.
- Return a positive value if the first object is greater than the second object.
We can write our own custom logic and return one integer value.
Create one file CarsComparator.java:
import java.util.Comparator;
public class CarsComparator implements Comparator<Car> {
@Override
public int compare(Car o1, Car o2) {
return o1.getColor().length() - o2.getColor().length();
}
}
This file is implementing the Comparator interface and overrides the compare method. If we use this comparator, it will sort the items in increasing order of the length of colors.
We can use he comparator to sort the ArrayList:
cars.sort(new CarsComparator());
for (Car car : cars) {
System.out.println(car);
}
It will print:
id: 1, color: Red
id: 5, color: Blue
id: 5, color: Green
id: 2, color: Gamboge
id: 1, color: Raspberry
Method 7: How to use a custom comparator:
Alternate to the above example, we can implement a Comparable interface to the Cars class. It will require to implement a method called compareTo, that will take one Car instance as the parameter. We have to write our own custom logic and return one integer value from this method.
- Return zero if both objects are equal.
- Return a negative value if the first object is less than the second object.
- Return a positive value if the first object is greater than the second object.
We can use Collections.sort() or stream sorted() method to sort an ArrayList.
For example, let’s change the Cars.java file as below:
public class Car implements Comparable<Car>{
int id;
String color;
public int getId() {
return id;
}
public String getColor() {
return color;
}
public Car(int id, String color) {
this.id = id;
this.color = color;
}
@Override
public String toString() {
return "id: " + id + ", color: " + color;
}
@Override
public int compareTo(Car o) {
return o.getColor().length() - this.getColor().length();
}
}
It will sort the objects in decreasing order of length of the color of each object.
Collections.sort(cars);
for (Car car : cars) {
System.out.println(car);
}
It will print:
id: 1, color: Raspberry
id: 2, color: Gamboge
id: 5, color: Green
id: 5, color: Blue
id: 1, color: Red
You might also like:
- 3 ways to find perfect numbers in a range in Java
- How to print a Hollow Rhombus pattern in Java
- Java program to print hollow diamond star pattern
- Java program to print a plus star pattern
- Java program to print X star pattern
- Java program to check if a character is Alphabet or not
- Java program to print from A to Z
- Java program to filter a map by key and value
- Java program to check if a number is perfect square or not