8

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.

user345280
  • 1,920
  • 2
  • 18
  • 24
  • 3
    possible duplicate of [How to sort an array of objects(Points) in Java?](http://stackoverflow.com/questions/3077746/how-to-sort-an-array-of-objectspoints-in-java) – BackSlash Jan 13 '15 at 19:03
  • I think Java 7 (Net Beans 7.4) – user345280 Jan 13 '15 at 19:06
  • You have to come up with some way to compare two `Person`(s); the usual way would be to make `Person` implement `Comparable` or to write a `Comparator`. They would be used to compare people. – Elliott Frisch Jan 13 '15 at 19:06

5 Answers5

28

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));
tobias_k
  • 81,265
  • 12
  • 120
  • 179
  • Keep it on , I am really happy with awesome people using functional programming features in java 8 :) – Abdelrahman Elkady Jan 13 '15 at 19:27
  • Using the Comparator is also more flexible (say, if you want to sort on different fields depending on UI input), since you can have more than one of them. – spudone Jan 13 '15 at 19:34
6

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

Sid
  • 563
  • 1
  • 10
  • 28
Abdelrahman Elkady
  • 2,518
  • 2
  • 21
  • 30
4

You can implement the Comparable interface to make your class comparable. Make sure to override the compareTo method then.

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

    @Override
    public int compareTo(Person p) {
        if(this.age < p.getAge()) return -1;
        if(this.age == p.getAge()) return 0;
        //if(this.age > p.getAge()) return 1;
        else return 1;
    }

    //also add a getter here
}
freeDom-
  • 362
  • 4
  • 20
  • 4
    I always confuse when to return `-1` and when `+1`, so I prefer `return Integer.compare(this.age, p.getAge())`. Shorter, and foolproof. – tobias_k Jan 13 '15 at 19:11
0

Yes just implement the Comparable interface.

Here's an example :

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

    public int compareTo(Person other){
        return this.age == other.age ? 0 : this.age > other.age ? 1 : -1;
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
0
import java.util.Arrays;

public class PersonCompare {

public static void main(String[] args) {
    Person p1 = new Person("Test1",10);
    Person p2 = new Person("Test2",12);
    Person p3 = new Person("Test3",4);
    Person p4 = new Person("Test4",7);

    Person[] ArrayOfPersons = {p1,p2,p3,p4};
    Arrays.sort(ArrayOfPersons);

    for(Person p: ArrayOfPersons) {
        System.out.println(p.getName()+"--"+p.getAge());
    }
}
}


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

Person(String name, int age){
    this.name=name; this.age=age;

}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public int getAge() {
    return age;
}

public void setAge(int age) {
    this.age = age;
}


@Override
public int compareTo(Person other) {
    if(this.getAge() > other.getAge())
        return 1;
    else if (this.getAge() == other.getAge())
        return 0 ;
    return -1 ;
}
}
A Baldino
  • 178
  • 1
  • 11