Java对一个对象的ArrayList按照姓氏和名字进行排序

bluesky5月前 ⋅ 65 阅读

ChatGPT的回答仅作参考:

可以通过实现Comparator接口来对一个对象的ArrayList按照姓氏和名字进行排序。

假设有一个Person类,包含firstName和lastName两个属性,可以按照以下方式实现排序:

```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Person {
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public static void main(String[] args) {
        ArrayList<Person> personList = new ArrayList<>();
        personList.add(new Person("John", "Doe"));
        personList.add(new Person("Jane", "Doe"));
        personList.add(new Person("Alice", "Smith"));
        personList.add(new Person("Bob", "Smith"));

        // 按照姓氏和名字排序
        Collections.sort(personList, new Comparator<Person>() {
            @Override
            public int compare(Person p1, Person p2) {
                int result = p1.getLastName().compareTo(p2.getLastName());
                if (result == 0) {
                    result = p1.getFirstName().compareTo(p2.getFirstName());
                }
                return result;
            }
        });

        // 输出排序结果
        for (Person person : personList) {
            System.out.println(person.getLastName() + ", " + person.getFirstName());
        }
    }
}
```

运行结果为:

```
Doe, Jane
Doe, John
Smith, Alice
Smith, Bob
```

全部评论: 0

    相关推荐