按字段排序对象数组

时间:2015-01-13 19:00:48

标签: java arrays sorting object field

我有对象

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

是否有一种简单的排序方式

Person[] ArrayOfPersons

按年龄?

我必须使用Comparable或Comparator吗?我不完全理解他们。

5 个答案:

答案 0 :(得分:11)

为了完整起见,在使用Java 8时,您可以使用Comparator.comparing为某些属性创建一个简单的比较器,例如Comparator.comparing(Person::getAge),或使用lambda,如Comparator.comparing(p -> p.age),如果没有年龄的getter方法。

这使得比较器使用thenComparing,例如比较器变得特别容易。主要按年龄排序,然后按关系名称排序:

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

将其与Arrays.sort相结合,您就完成了。

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

答案 1 :(得分:4)

您可以实施Comparable接口以使您的班级具有可比性。确保覆盖compareTo方法。

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
}

答案 2 :(得分:3)

您可以使用循环中的getter检查年龄

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

然而,实施Comparable是一种方便的方法

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

您也可以查看Comparable文档

答案 3 :(得分:0)

是的,只需实施Comparable界面。

以下是一个例子:

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

答案 4 :(得分: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 ;
}
}
相关问题