Possible Duplicate:
Sorting an ArrayList of Contacts based on name?
Sorting of ArrayList
I have an ArrayList
of type Person
and I want to sort it based on the person's ages: person.getAge()
.
How can I do that, so that the list of people is ordered by their age?
4 Answers 4
ArrayList<Person> people = . . .;
Collections.sort(people, new Comparator<Person>() {
@Override
public int compare(Person o1, Person o2) {
final int age1 = o1.getAge();
final int age2 = o2.getAge();
return age1 < age2 ? -1 : age1 > age2 ? 1 : 0;
}
}
);
In Java 7, you can use return Integer.compare(age1, age2);
instead.
Alternatively, you can have Person
implement Comparable<Person>
. However, then you could only sort on the one attribute.
4 Comments
Integer.compare(int, int)
?Boolean
implements Comparable<Boolean>
. It treats true
as greater than false
.Expanding on the comment, something along these lines:
Collections.sort(personList, new Comparator<Person>() {
@Override
public int compare(Person p1, Person p2) {
return new Integer(p1.getAge()).compareTo(p2.getAge());
}
});
Relevant documentation
Comments
//We can do using TreeMap
//i.e
TreeMap treemap=new TreeMap<int,Person>
//trace over person
for(Person p:YourPersonArrayList)
{
treemap.put(p.getAge(),p);
}
//Finally you get TreeMap which is
//sorted on Persons age...
1 Comment
Define your comparator
, which compares using the age
attribute Only. Use the same in collection sort method [sort(java.util.List, java.util.Comparator)](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#sort(java.util.List, java.util.Comparator)) which accepts the comparator.
Collections.sort(peopleList, new Comparator<Person>(){
@Override
public int compare(Person p1, Person p2) {
return Integer.valueOf(p1.getAge()).compareTo(p2.getAge());
}
});
Or better do below for optimization as Integer.compareTo
internally uses Integer.compare
method.
Collections.sort(peopleList, new Comparator<Person>(){
@Override
public int compare(Person p1, Person p2) {
return Integer.compare(p1.getAge(), p2.getAge());
}
});
3 Comments
Integer
objects for each comparison. Much better to stick to primitive int
comparisons.Integer.compare
method which does the comparison of tow int values for you. I would advice not to implement a custom comparison.
Comparator
interface andCollections.sort(...)
method