5 ways to sort an array of custom objects by property in java with examples
It is a short tutorial on multiple ways to sort an array of objects in java.
Let’s define an Employee.java
class.
public class Employee {
private Integer id;
private String name;
private Integer salary;
public Employee(Integer id, String name,Integer salary) {
this.id = id;
this.name = name;
this.salary=salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return "{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
}
Employee
class fields - id
, name
and salary
Let’s add some data and display the ArrayList
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Employee> list=new ArrayList<>();
Employee e1=new Employee(1,"Franc",5000);
Employee e2=new Employee(11,"John",8000);
Employee e3=new Employee(12,"Eric",4000);
Employee e4=new Employee(14,"Andrew",7000);
list.add(e1);
list.add(e2);
list.add(e3);
list.add(e4);
System.out.println(list);
}
}
Output:
[{id=1, name='Franc', salary=5000},
{id=11, name='John', salary=8000},
{id=12, name='Eric', salary=4000},
{id=14, name='Andrew', salary=7000}]
In the above example,
- Created
List
ofEmployee
objects - Populate
ArrayList
withemployee
data - Finally, Print a list of employee objects
- List objects are displayed in
insert
order by default.
sort ArrayList of objects by property java
There are multiple ways we can sort objects by property We will see multiple ways to sort employee
objects with salary in ascending
or descending
order.
Using java.util.Comparator
Collections class provides a sort method that accepts two arguments.
- list argument is the source array list to sort
- Comparator object which has compared method
Collections.sort(list, new Comparator<Employee>(){
public int compare(Employee e1, Employee e2){
return e1.getSalary().compareTo(e2.getSalary());
}
});
System.out.println(list);
Output:
[{id=12, name='Eric', salary=4000},
{id=1, name='Franc', salary=5000},
{id=14, name='Andrew', salary=7000},
{id=11, name='John', salary=8000}]
Sort list of Employee
Object in salary field descending
order
Collections.sort(list, new Comparator<Employee>(){
public int compare(Employee e1, Employee e2){
return e2.getSalary().compareTo(e1.getSalary());
}
});
System.out.println(list);
Output
[{id=11, name='John', salary=8000},
{id=14, name='Andrew', salary=7000},
{id=1, name='Franc', salary=5000},
{id=12, name='Eric', salary=4000}]
The following logic returns the list in descending order
return e1.getSalary().compareTo(e2.getSalary());
for ascending order
return e2.getSalary().compareTo(e1.getSalary());
Java 8 sort objects list by field
java 8
extended comparator
behavior and added comparing
static method.
Syntax for Comparting:
static <T,U extends Comparable<? super U>> Comparator<T> comparing(
Function<? super T,? extends U> keyExtractor)
static <T,U> Comparator<T> comparing(
Function<? super T,? extends U> keyExtractor,
Comparator<? super U> keyComparator)
Comparing method has the below arguments.
keyExtractor
: key function to sort keyComparator
: Optional to add custom logic comparison.
This comparator
can be applied to List
as well as Collections
classes. Here is an example sort list by fields ascending with List and Collections.
list.sort(Comparator.comparing(Employee::getSalary)); (or)
Collections.sort(list,Comparator.comparing(Employee::getSalary));
To sort descending
list.sort(Comparator.comparing(Employee::getSalary,(emp1, emp2) -> {
return emp2.compareTo(emp1);
}));
Collections.sort(list,Comparator.comparing(Employee::getSalary,(emp1, emp2) -> {
return emp2.compareTo(emp1);
}));
Custom object with Comparable class
It is an example of sorting object lists with property alphabetically.
Let’s implement Comparable in Employee object override compareTo
with custom logic, Here Need sorting based on employee name, so getName field logic added to this method.
public class Employee implements Comparable<Employee>{
private Integer id;
private String name;
private Integer salary;
public Employee(Integer id, String name,Integer salary) {
this.id = id;
this.name = name;
this.salary=salary;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSalary() {
return salary;
}
public void setSalary(Integer salary) {
this.salary = salary;
}
@Override
public String toString() {
return "{" +
"id=" + id +
", name='" + name + '\'' +
", salary=" + salary +
'}';
}
@Override
public int compareTo(Employee u) {
if (getName() == null || u.getName() == null) {
return 0;
}
return getName().compareTo(u.getName());
}
}
Object with name are sorted alphabetically
i.e ascending
order
Collections.sort(list);
Descending order
Collections.sort(list);
Collections.reverse(list);
Sort using Java8 stream sorted
This approach returns a new array list.
iterate ArrayList using stream()
use the sorted method to return the element in sorted
finally returns the collection to the list
List<Employee> result = (ArrayList<Employee>) list
.stream().sorted(Comparator.comparing(Employee::getName))
.collect(Collectors.toList());
Sort ArrayList of Objects by multiple properties
Here is a sequence of steps
- First, create a
Comparator
using theComparator. comparing
method - In this comparator, Sorting first
id
, nextname
andsalary
. - Pass this
comparator
toList
for soring usingList
. - pass this
comparator
toList
for sorting usingCollections
. - Comparator returns a list in
ascending
order - Comparator.
reverse
returns list indescending
order
Comparator<Employee> employeeComparator = Comparator.comparing(Employee::getId)
.thenComparing(Employee::getName)
.thenComparing(Employee::getSalary);
Collections.sort(list, employeeComparator);
Example for Sorting multiple fields with list
and collections
in ascending
order
Collections.sort(list, employeeComparator); // ascending
list.sort(employeeComparator);
Example for Sorting multiple fields with list
and collections
in descending
order
Collections.sort(list, employeeComparator.reversed());
list.sort(employeeComparator.reversed());