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) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public String getId() {
return id;
}
public int getAge() {
return age;
}
@Override
public int compareTo(Employee other) {
return Integer.compare(this.age, other.age);
}
@Override
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)
Collections.sort(employees);
System.out.println(employees);
}
}