开发者

Sorting an ArrayList dependent on the elements field

I have an arraylist of objects with an age field internal to the objects. How can I sort 开发者_开发知识库them in ascending order dependant on their age?

Thanks for your time


Provide a comparator e.g.

Collections.sort(list, new Comparator<MyType>() {
   public int compareTo(MyType t1, MyType t2) {
      return t1.age - t2.age;
   }
}

If the age can be a large range, this is not safe, but I assume the age will be between 0 and 2 billion. ;)


The Google Guava way to do this would be best I think:

Collections.sort(list, Ordering.natural().onResultOf(Person.ageFunction()));

This assumes the existence of Person.ageFunction():

public Function<Person, Integer> ageFunction() {
  return new Function<Person, Integer>() {
    @Override public Integer apply(Person person) {
      return person.age;
    }
  };
}

Both Ordering and Google Guava are super handy, should be a tool in any Java programmer's toolbox. See the Guava home page.


Whenever you're comparing things that don't have a natural, consistent ordering, you shouldn't be implementing Comparable. Implement a Comparator instead. The reason for this is that the criteria for sorting is not intrinsic to the object...who can say that a 12 year old is "greater" than an 11 year old? What if the 11 year old is taller? Has an earlier birthday? Comparisons like these are arbitrary and are relevant to the context in which they are used, not intrinsically to the person itself.

This doesn't necessarily mean you have to expose any more data. You can easily expose the Comparator while still encapsulating the age field if you prefer. Something like this:

class Person {
   int age;

   public Comparator<Person> ageComparator() {
      return new Comparator<Person>() {

         public int compare(Person a, Person b) {
             if ( a.age > b.age ) {
                return 1;
             } else if ( a.age < b.age ) {
                return -1;
             } else {
                return 0;
             }
         }
       };
   }
} 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜