How to solve – ” method sort(List) in the type Collections is not applicable for the arguments (List<>): “

Fri, Nov 15, 2019

Read in 1 minutes

I have Employee class and I want to sort the employees by name order.

When I call sort method from java.lang.Collection class, I get the error.

sortingerror

To solve this error, you have to implement the employee class with a Comparable Interface or Comparator Interface.

If you want to sort by a single property(E.g: sort by name), you can use Comparable Interface. If you want to sort by multiple properties(E.g by “name” and “experienceYears”), you have to implement the comparator interface.

Check the sorting using Comparable Interface Object Sorting

Image text

public class SortingDemoTWO {
        public void createArrayAndSort(){
        List<Employee> empList =new ArrayList<Employee>();
        Employee e1=new Employee("bob",3,5);
        Employee e3=new Employee("Tony",5,4);
        Employee e4=new Employee("Ann",4,5);
        Employee e5=new Employee("Rey",5,4);
        Employee e6=new Employee("Jack",4,4);
        empList.add(e1);
        empList.add(e3);
        empList.add(e4);
        empList.add(e5);
        empList.add(e6);
        Collections.sort(empList,Employee.empNameComparator);
        for(Employee e:empList) {
          System.out.println("Name "+e.getName()+"Years of Exp "+
                e.getExperienceYears()+"");
        }
        Collections.sort(empList,Employee.empExpYearsComparator);
        for(Employee e:empList) {
          System.out.println("Name  "+e.getName()+"   "+"Years of Exp  "+
                e.getExperienceYears()+"");
            }
        }
        public static void main(String[] args) {
        SortingDemoTWO sort=new SortingDemoTWO();
        sort.createArrayAndSort();
        }
        }

Points to remember :

If you want to use Collections.sort(list), the list should implement the Comparable or Comparator interface