How to sort an array of objects by a string property value ?

This sneppet will guide you on how to sort an array of objects by a string property value in Java by implementing a custom comparator and using the Collections.sort() method.

Sort an array of objects by a string property value

Here’s an example assuming you have a class EmployeeObject with a name property and you want to sort by the property “name” value:

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

class EmployeeObject {

    String name;

    String city;

    public EmployeeObject (String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }
  
    public String getCity() {
        return city;
    }
}

public class SortExample {

    public static void main(String[] args) {

        List<EmployeeObject > list = new ArrayList<>();
        list.add(new EmployeeObject ("Joe", "New York"));
        list.add(new EmployeeObject ("Daniel", "Los Angeles"));
        list.add(new EmployeeObject ("Mike", "Chicago"));

        Collections.sort(list, Comparator.comparing(EmployeeObject::getName));

        for (EmployeeObject obj : list) {
            System.out.println(obj.getName());
        }

    }

}

In this example, we create a custom comparator using Comparator.comparing() method to compare objects based on the name property. Then we call Collections.sort() passing the list and the custom comparator to sort the list of objects by the name property.

How does the Comparator comparing works ?

The Comparator.comparing is a feature introduced in Java 8 as part of the java.util.Comparator package.

The comparator interface provides a static method called comparing that allows you to specify sort key (for example, name property) to compare objects. This method is used to extract a value from an object (EmployeeObject) and compare it against that value during sorting.

Note, the main advantage of using Comparator.comparing method is for its flexibility. Basically, it allows sorting based on different fields of the Object and we can also create a complex sorting logic in easier manner as shown in the example above.

You’ll also like:

References

 

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments