Thursday, May 17, 2018

Sort employee object base on salary & location both

Problem statement: Sort employee record based on salary & location.

  1. import java.util.List;
  2. import java.util.Arrays;
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;

  6. class EmployeeExe1 {
  7. String name;
  8. Double salary;
  9. String location;
  10. EmployeeExe1(String name, Double salary, String location) {
  11. this.name = name;
  12. this.salary = salary;
  13. this.location = location;
  14. }
  15. public String toString() {
  16. return "name: " + name + ", salary: " + salary + ", location: " + location;
  17. }
  18. }

  19. class SortEmpBySalary implements Comparator<EmployeeExe1> {
  20. public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
  21. if (e1.salary.compareTo(e2.salary) > 0) {
  22. return 1;
  23. }
  24. if (e1.salary.compareTo(e2.salary) < 0) {
  25. return -1;
  26. }
  27. return 0;
  28. }
  29. }

  30. class SortEmpByLocation implements Comparator<EmployeeExe1> {
  31. public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
  32. return e1.location.compareTo(e2.location);
  33. }
  34. }

  35. class SortByTwoFields implements Comparator<EmployeeExe1> {
  36. List<Comparator<EmployeeExe1>> empAll;

  37. @SafeVarargs
  38. public SortByTwoFields(Comparator<EmployeeExe1>... e2) {
  39. this.empAll = Arrays.asList(e2);
  40. }

  41. @Override
  42. public int compare(EmployeeExe1 o1, EmployeeExe1 o2) {
  43. for (Comparator<EmployeeExe1> x : empAll) {
  44. int res = x.compare(o1, o2);
  45. if (res != 0) {
  46. return res;
  47. }
  48. }
  49. return 0;
  50. }
  51. }

  52. public class SortEmplyeeBySalLoc {
  53. public static void main(String[] args) {
  54. List<EmployeeExe1> l = new ArrayList<EmployeeExe1>();
  55. l.add(new EmployeeExe1("ishaan", 12000.00, "blr"));
  56. l.add(new EmployeeExe1("raju", 11000.00, "hyd"));
  57. l.add(new EmployeeExe1("ritesh", 9000.00, "del"));
  58. l.add(new EmployeeExe1("nikash", 9000.00, "mum"));

  59. Collections.sort(l, new SortByTwoFields(new SortEmpBySalary(), new SortEmpByLocation()));
  60. for (Object o : l) {
  61. System.out.println(o);
  62. }
  63. }
  64. }
Output:

name: ritesh, salary: 9000.0, location: del
name: nikash, salary: 9000.0, location: mum
name: raju, salary: 11000.0, location: hyd
name: ishaan, salary: 12000.0, location: blr

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...