Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have objects

Person{
    String name;  
    int age;
    float gradeAverage;
    }

Is there an easy way to sort

Person[] ArrayOfPersons

by age?

Do I have to use Comparable or Comparator? I don't fully understand them.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
387 views
Welcome To Ask or Share your Answers For Others

1 Answer

Just for completeness, when using Java 8, you can use Comparator.comparing to create a simple comparator for some attribute, e.g. Comparator.comparing(Person::getAge), or using lambda, like Comparator.comparing(p -> p.age), if there is not getter method for the age.

This makes it particularly easy to chain comparators for different attributes, using thenComparing, e.g. for sorting primarily by age, and then by name in case of ties:

Comparator.comparing(Person::getAge).thenComparing(Person::getName)

Combine that with Arrays.sort, and you are done.

Arrays.sort(arrayOfPersons, Comparator.comparing(Person::getAge));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...