How to sort a linked list in some natural order?

We have a linked list, the elements of this linked list are Employee, I want to sort this linked list based on the Employee salary, the salary is one of the members of the Employee class, can Collections.sort () be used? if not, how can I sort it? Can someone explain to me?

+4
source share
4 answers

Yes, you can use Collections.sort()

You need your Employee class to implement the Comparable interface.

http://download.oracle.com/javase/6/docs/api/java/lang/Comparable.html

In your compareTo() method, you compare the salary of the current object with the database of the object.

Edit:

Another option you have if you do not want this comparison by default to create a Comparator object and use the second form -> Collections.sort(List, Comparator);

It will look like this:

 class SalaryComparator implements Comparator<Employee> { public int compare(Employee e1, Employee e2) { if (e1.getSalary() > e2.getSalary()) return 1; else if (e1.getSalary() < e2.getSalary()) return -1; else return 0; } } 

Now you can do: Collections.sort(myEmployeeList, new SalaryComparator());

+6
source

While LinkedList<Employee> working, I would use ArrayList<Employee> for this:

 List<Employee> employees = new ArrayList<Employee>(); 

After you have filled it (in any case), you can sort it by salary as follows:

 Collections.sort(employees, new Comparator<Employee>() { public int compare(Employee e1, Employee e2) { return e1.getSalary() - e2.getSalary(); } }); 
+4
source

You can use Collections.sort()

But for this, your Employee class must first implement the Comparable interface.

Example example:

 public class Employee implements Comparable<Employee> { public int compareTo(Employee e) { return this.salary - e.salary; } } 
0
source

You can sort the linked list, but this is not an efficient operation, especially if the list is not trivial in size. Select the appropriate data structures.

0
source

All Articles