Problem statement: Sort employee record based on salary & location.
- import java.util.List;
- import java.util.Arrays;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- class EmployeeExe1 {
- String name;
- Double salary;
- String location;
- EmployeeExe1(String name, Double salary, String location) {
- this.name = name;
- this.salary = salary;
- this.location = location;
- }
- public String toString() {
- return "name: " + name + ", salary: " + salary + ", location: " + location;
- }
- }
- class SortEmpBySalary implements Comparator<EmployeeExe1> {
- public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
- if (e1.salary.compareTo(e2.salary) > 0) {
- return 1;
- }
- if (e1.salary.compareTo(e2.salary) < 0) {
- return -1;
- }
- return 0;
- }
- }
- class SortEmpByLocation implements Comparator<EmployeeExe1> {
- public int compare(EmployeeExe1 e1, EmployeeExe1 e2) {
- return e1.location.compareTo(e2.location);
- }
- }
- class SortByTwoFields implements Comparator<EmployeeExe1> {
- List<Comparator<EmployeeExe1>> empAll;
- @SafeVarargs
- public SortByTwoFields(Comparator<EmployeeExe1>... e2) {
- this.empAll = Arrays.asList(e2);
- }
- @Override
- public int compare(EmployeeExe1 o1, EmployeeExe1 o2) {
- for (Comparator<EmployeeExe1> x : empAll) {
- int res = x.compare(o1, o2);
- if (res != 0) {
- return res;
- }
- }
- return 0;
- }
- }
- public class SortEmplyeeBySalLoc {
- public static void main(String[] args) {
- List<EmployeeExe1> l = new ArrayList<EmployeeExe1>();
- l.add(new EmployeeExe1("ishaan", 12000.00, "blr"));
- l.add(new EmployeeExe1("raju", 11000.00, "hyd"));
- l.add(new EmployeeExe1("ritesh", 9000.00, "del"));
- l.add(new EmployeeExe1("nikash", 9000.00, "mum"));
- Collections.sort(l, new SortByTwoFields(new SortEmpBySalary(), new SortEmpByLocation()));
- for (Object o : l) {
- System.out.println(o);
- }
- }
- }
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