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:
- Python program to find difference between two given numbers
- Access and process nested objects, arrays, or JSON ?
- Java Palindrome Program- Check String or Number is Palindrome
- Program to Check Given Number is Odd or Even
- Convert single digit number to double digits string
- Find the greatest of three numbers
- Most Common Element in an Unsorted Array
- Get Common Elements between Two Unsorted Arrays
- Implement Stack using Linked List
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not ‘str’ – Python3
- Extract numbers from a string in python
- Java String substring() example program
- Find which users belongs to a specific group in linux
- print multiplication table for any number
- Check if Python Object is a Number ?
- In-place merge sort instead of normal merge sort ?
- Ways to print arrays in Java
References