簡體   English   中英

按字段排序對象數組

[英]Sorting array of objects by field

我有對象

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

有一種簡單的排序方式

Person[] ArrayOfPersons

按年齡?

我必須使用Comparable或Comparator嗎? 我不完全理解他們。

為了完整Comparator.comparing(Person::getAge) ,在使用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));

您可以實現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
}

您可以在循環中使用吸氣劑檢查年齡

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文檔

是的,只需實現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;
    }
}
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 ;
}
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM