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.
Read full article from java - How do I sort an ArrayList based on its object's contents - Stack Overflow
No comments:
Post a Comment