Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of objects by field

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.

like image 832
user345280 Avatar asked Jan 13 '15 19:01

user345280


2 Answers

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));
like image 142
tobias_k Avatar answered Sep 25 '22 02:09

tobias_k


You can check for age using a getter in your loop

for (int i = 0 ; i < persons.length - 1; i++) {
    Person p = persons[i];
    Person next =  persons[i+1];
    if(p.getAge() > next.getAge()) {
        // Swap
    }
}

However implementing Comparable is the convenient way

class Person implements Comparable<Person> {
    String name;  
    int age;
    float gradeAverage;

    public int compareTo(Person other) {
        if(this.getAge() > other.getAge())
            return 1;
        else if (this.getAge() == other.getAge())
            return 0 ;
        return -1 ;
    }

    public int getAge() {
        return this.age ;
    }
}

You can check Comparable documentation also

like image 21
Abdelrahman Elkady Avatar answered Sep 21 '22 02:09

Abdelrahman Elkady