📅  最后修改于: 2023-12-03 14:44:58.155000             🧑  作者: Mango
In Java, sorting an ArrayList of objects by one or more fields requires implementing the Comparable
interface and overriding the compareTo
method. When sorting a list of objects with multiple fields, such as last name and first name, we need to define a custom comparison logic that considers both fields.
Here's an example showing how to sort an ArrayList of objects by last name and first name in Java:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class Person implements Comparable<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;
}
@Override
public int compareTo(Person other) {
int lastNameComparison = lastName.compareTo(other.getLastName());
if (lastNameComparison != 0) {
return lastNameComparison;
}
return firstName.compareTo(other.getFirstName());
}
@Override
public String toString() {
return firstName + " " + lastName;
}
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
people.add(new Person("John", "Doe"));
people.add(new Person("Alice", "Smith"));
people.add(new Person("Mary", "Johnson"));
people.add(new Person("David", "Brown"));
// Sort by last name and first name
Collections.sort(people);
// Print sorted list
for (Person person : people) {
System.out.println(person);
}
}
}
In this example, we have a Person
class with firstName
and lastName
fields. The compareTo
method is implemented to compare the last names first and then the first names if the last names are the same. This ensures that the list of Person
objects is sorted first by last name and then by first name.
To sort the ArrayList, we use the Collections.sort
method, which internally uses the overridden compareTo
method to compare the objects.
The output of the above code will be:
David Brown
John Doe
Mary Johnson
Alice Smith
The list is sorted in ascending order by last name and then by first name.
Remember, when comparing strings, use the compareTo
method instead of the ==
operator as it performs a lexicographic comparison.
Using this approach, you can easily sort an ArrayList of objects by multiple fields in Java.