3

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.

a1204773
  • 6,923
  • 20
  • 64
  • 94

2 Answers2

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.

Community
  • 1
  • 1
Sumit
  • 1,661
  • 1
  • 13
  • 18