Sort Employee Objects on Age

This program defines an Employee class with properties of name, id, and age, and implements the Comparable interface to enable sorting by age. The main method creates a list of 100 employee objects and sorts them based on age using the Collections.sort method. Finally, the sorted list of employees is printed to the console.

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

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

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

    public String getName() {
        return name;

    public String getId() {
        return id;

    public int getAge() {
        return age;

    public int compareTo(Employee other) {
        return, other.age);

    public String toString() {
        return "Employee{" +
                "name='" + name + '\'' +
                ", id='" + id + '\'' +
                ", age=" + age +

    public static void main(String[] args) {
        // Create a list of 100 employee objects
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("John", "1001", 25));
        employees.add(new Employee("Jane", "1002", 30));
        employees.add(new Employee("Bob", "1003", 28));
        // ... and so on for the other 97 employees

        // Sort the list of employees based on age (ascending order)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.