[Solved] How can i sort objects in arrayList? [closed]

Use Comparable and Comparator as shown below, you can also visit https://www.journaldev.com/780/comparable-and-comparator-in-java-example for further details.

    import java.util.Comparator;

    class Employee implements Comparable<Employee> {

        private int id;
        private String name;
        private int age;
        private long salary;

        public int getId() {
            return id;

        public String getName() {
            return name;

        public int getAge() {
            return age;

        public long getSalary() {
            return salary;

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

        public int compareTo(Employee emp) {
            //let's sort the employee based on id in ascending order
            //returns a negative integer, zero, or a positive integer as this employee id
            //is less than, equal to, or greater than the specified object.
            return (this.id - emp.id);

        //this is required to print the user friendly information about the Employee
        public String toString() {
            return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
                    this.salary + "]";

Default Sorting of Employees list:
[[id=1, name=Pankaj, age=32, salary=50000], [id=5, name=Lisa, age=35, salary=5000], [id=10, name=Mikey, age=25, salary=10000], [id=20, name=Arun, age=29, salary=20000]]

solved How can i sort objects in arrayList? [closed]