I have one ArrayList<Users> users_list;
and in users i have name, surname, age etc. I want to implement an sorting algorithm that will sort my arraylist based on users age. I searched a lot but found only for sorting arrays.
Asked
Active
Viewed 4,492 times
2 Answers
6
Use a custom java.util.Comparator
:
public class UserComparator implements Comparator<User> {
@Override
public int compare(User u1, User u2) {
return u1.getAge().compareTo(u2.getAge());
}
}
And sort it like:
Collections.sort(users_list, new UserComparator());

acdcjunior
- 132,397
- 37
- 331
- 304
0
Take a look here. JavaBeans Comparison. The second answer seems to be more to the point.
I would suggest using http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections/ComparatorUtils.html#naturalComparator()
as the comparator parameter of the BeanComparator.