Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 

 1 Answer(s)

  • Hi Babita, we can sort ArrayList in different ways using Comparator, Comparable classes and some others ways also, but as you said that you want it without using Collections class. Then you can use the TreeSet class to sort the ArrayList using the Comparator. For example :

    public class SalaryComparator implements Comparator<Employee> {
      public int compare(Employee emp1, Employee emp2) {
        if (emp1.getSalary() == emp2.getSalary()) {
          return 0;
        } else {
          return emp1.getSalary() < emp2.getSalary() ? -1 : 1;
      }
    }
    

    In main class :

    List<Employee> employeeList = new ArrayList<Employee>();
    employeeList.add(new Employee("Akash", 25000));
    employeeList.add(new Employee("Rajesh", 12000));
    employeeList.add(new Employee("Harsh Singh", 20000));
    
    for (Employee employee : employeeList) {
       System.out.println(employee);
    }
    
    SortedSet<Employee> sortedListBySalary = new TreeSet<Employee>(new SalaryComparator());
    sortedListBySalary.addAll(employeeList);
    for (Employee employee : sortedListBySalary) {
       System.out.println(employee);
    }
    

    I hope this will help you.

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: