EN
Java - sort ArrayList based on Object field
0
points
In this article, we would like to show you how to sort ArrayList in a custom sorting order based on Object field in Java.
Quick solution:
users.sort(new Comparator<User>() {
public int compare(User u1, User u2) {
if (u1.getAge() == u2.getAge())
return 0;
return u1.getAge() < u2.getAge() ? -1 : 1;
}
});
Practical example
In this example, we create a custom Comparator
that will help us to sort users
ArrayList by users age
.
import java.util.*;
public class Example {
public static void main(String[] args) {
User user1 = new User(1, "Tom", 24);
User user2 = new User(2, "Kate", 22);
User user3 = new User(3, "Ann", 25);
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
System.out.println("Before: " + users);
users.sort(new Comparator<User>() {
public int compare(User u1, User u2) {
if (u1.getAge() == u2.getAge())
return 0;
return u1.getAge() < u2.getAge() ? -1 : 1;
}
});
System.out.println("After: " + users);
}
}
Output:
Before: [User{ id=1, name='Tom', age=24 }, User{ id=2, name='Kate', age=22 }, User{ id=3, name='Ann', age=25 }]
After: [User{ id=2, name='Kate', age=22 }, User{ id=1, name='Tom', age=24 }, User{ id=3, name='Ann', age=25 }]
Note:
We are able to print
users
in the Example class, because we have overriddentoString()
method in the User class.
User class:
public class User {
private final int id;
private final String name;
private final int age;
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "User{ " +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
" }";
}
}