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.

0

2 Answers 2

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());
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.