Sorting
Programming
Object-oriented Programming
Data Structures
Code Optimization

How do I sort a list of objects based on an attribute of the objects?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

When working with collections of objects in programming, a frequently encountered task is sorting these objects based on specific attributes. This process can vary significantly across different programming languages and may involve built-in functions or require custom functions. This article explores various methods of sorting lists of objects, using Python as a primary example but also touching on other languages like Java and JavaScript for comparison.

Sorting in Python

Python is known for its robust built-in features that simplify many common programming tasks, including sorting. Lists of objects can be sorted in Python using the sort() method or the sorted() function. These tools provide a way to define the sorting criteria explicitly through a key function.

Using sort() and sorted() with a key parameter

The sort() method is used to sort a list in place, meaning it modifies the original list. In contrast, the sorted() function returns a new list, leaving the original unaltered. Both can accept a key parameter, which is a function that returns the attribute to sort by.

Example: Sorting a list of instances of a Person class by age attribute.

python
1class Person:
2    def __init__(self, name, age):
3        self.name = name
4        self.age = age
5
6    def __repr__(self):
7        return f"{self.name}({self.age})"
8
9# Creating a list of Person objects
10people = [Person("John", 30), Person("Sarah", 25), Person("Alice", 32)]
11
12# Sorting by age
13people_sorted = sorted(people, key=lambda person: person.age)
14
15print(people_sorted)  # Output: [Sarah(25), John(30), Alice(32)]

In this example, the lambda function lambda person: person.age serves as the key function, returning the age based on which the sort is performed.

Sorting in Java

Java provides several ways to sort objects, including using Collections.sort() with a custom Comparator.

Example: Sorting objects using a custom Comparator.

java
1import java.util.*;
2
3class Person {
4    String name;
5    int age;
6
7    Person(String name, int age) {
8        this.name = name;
9        this.age = age;
10    }
11
12    public String toString() {
13        return this.name + "(" + this.age + ")";
14    }
15}
16
17class AgeComparator implements Comparator<Person> {
18    public int compare(Person a, Person b) {
19        return a.age - b.age;
20    }
21}
22
23public class Main {
24    public static void main(String[] args) {
25        List<Person> people = new ArrayList<>(Arrays.asList(
26            new Person("John", 30),
27            new Person("Sarah", 25),
28            new Person("Alice", 32)
29        ));
30
31        Collections.sort(people, new AgeComparator());
32
33        System.out.println(people);
34    }
35}

In Java, custom comparators are typically implemented by defining a class that implements the Comparator interface. This provides complete control over how the objects are compared.

Sorting in JavaScript

JavaScript arrays can be sorted using the sort() method. This method can also take a comparator function.

Example: Sorting an array of objects by a property.

javascript
1let people = [
2    { name: "John", age: 30 },
3    { name: "Sarah", age: 25 },
4    { name: "Alice", age: 32 }
5];
6
7people.sort((a, b) => a.age - b.age);
8
9console.log(people);

The JavaScript sort() function is versatile, as the comparator function only needs to return a negative, zero, or positive value based on the comparison.

Summary Table

LanguageFunction/MethodCustomization MethodIn-place/Returns New
Pythonsorted(), sort()key functionBoth options
JavaCollections.sort()Comparator interfaceIn-place
JavaScriptsort()Comparator functionIn-place

Conclusion

Sorting a list of objects by an attribute is a common task in programming that can be approached in multiple ways depending on the language. Python provides a particularly straightforward and flexible approach, but Java and JavaScript also offer robust methods with their own strengths. Understanding the sorting mechanisms of each language improves the ability to manage data efficiently and perform critical operations like searching and data manipulation based on sorted results.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms