November 11, 2024

An example of a Java program that sorts a list of employees by their age

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

class Employee implements Comparable<Employee> {
    private int age;
    private String name;

    public Employee(int age, String name) {
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public String getName() {
        return name;
    }

    @Override
    public int compareTo(Employee o) {
        return Integer.compare(this.age, o.age);
    }

    @Override
    public String toString() {
        return "Employee [age=" + age + ", name=" + name + "]";
    }
}

public class SortEmployees {
    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee(25, "John"));
        employees.add(new Employee(30, "Jane"));
        employees.add(new Employee(20, "Bob"));
        employees.add(new Employee(35, "Emily"));

        System.out.println("Original List: " + employees);
        Collections.sort(employees);
        System.out.println("Sorted List: " + employees);
    }
}

In this example, the Employee class implements the Comparable interface and provides a custom implementation of the compareTo() method. This allows us to sort the employees list based on the age field of each Employee object.

The result is a sorted list of employees that is printed to the console.

Leave a Reply

Your email address will not be published. Required fields are marked *