Sorting array of objects by field

前端 未结 5 1683
北恋
北恋 2021-01-19 16:12

I have objects

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

Is there an easy way to sort

Person[]         


        
5条回答
  •  猫巷女王i
    2021-01-19 17:00

    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));
    

提交回复
热议问题