-
How to sort array without using Collection.sort method?
almost 8 years ago
-
almost 8 years ago
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.
-
1 Answer(s)