How to Sort a Collection of Custom Objects by Multiple Properties
Collections.sort proves useful for sorting simple data types such as strings. However, when dealing with custom objects, sorting based on specific properties can be challenging.
Consider a Person class with properties like name, age, and country. To sort a list of Person objects, we need a customized approach.
Introducing the Comparator Interface
The solution lies in implementing the Comparator interface, which provides a comparison method to define a sorting order. By overriding the compare() method, we can specify the sorting logic based on the desired property.
public class PersonComparator implements Comparator<Person> { // Define the sorting order as an enum public enum Order { NAME, AGE, COUNTRY } private Order sortingBy = Order.NAME; @Override public int compare(Person person1, Person person2) { switch (sortingBy) { case NAME: return person1.getName().compareTo(person2.getName()); case AGE: return person1.getAge().compareTo(person2.getAge()); case COUNTRY: return person1.getCountry().compareTo(person2.getCountry()); default: throw new RuntimeException("Invalid sorting order"); } } // Method to set the sorting order public void setSortingBy(Order sortingBy) { this.sortingBy = sortingBy; } }
Using the Comparator
To sort the personList by a specific property, we can create an instance of the PersonComparator and set the desired sorting order.
public void sortPersonList(Order sortingBy) { PersonComparator comparator = new PersonComparator(); comparator.setSortingBy(sortingBy); Collections.sort(personList, comparator); }
By calling the sortPersonList() method with the appropriate sorting order, we can achieve a sorted list based on the specified property. This approach provides flexibility and allows for sorting by multiple properties without modifying the Person class itself.
The above is the detailed content of How to Sort a List of Custom Objects by Multiple Properties in Java?. For more information, please follow other related articles on the PHP Chinese website!