Saturday, August 6, 2016

Sort a list by multiple attibute - chained comparator

sorting a list of employees by their job title, then by age, and then by salary

chained comparator -  CompareToBuilder class of the Apache Commons Lang library.

public class Employee {
    private String name;
    private String jobTitle;
    private int age;
    private int salary;
    public Employee(String name, String jobTitle, int age, int salary) {
        this.name = name;
        this.jobTitle = jobTitle;
        this.age = age;
        this.salary = salary;
    }
     // getters and setters
     public String toString() {
        return String.format("%s\t%s\t%d\t%d", name, jobTitle, age, salary);
    }

}

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
/**
 * This is a chained comparator that is used to sort a list by multiple
 * attributes by chaining a sequence of comparators of individual fields
 * together.
 *
 */
public class EmployeeChainedComparator implements Comparator {
    private List> listComparators;

    @SafeVarargs
    public EmployeeChainedComparator(Comparator... comparators) {
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        for (Comparator comparator : listComparators) {
            int result = comparator.compare(emp1, emp2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }

}

import java.util.Comparator;
/**
 * This comparator compares two employees by their job titles.
 *
 */
public class EmployeeJobTitleComparator implements Comparator {
    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getJobTitle().compareTo(emp2.getJobTitle());
    }

}

import java.util.Comparator;
/**
 * This comparator compares two employees by their ages.
 *
 */
public class EmployeeAgeComparator implements Comparator {
    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getAge() - emp2.getAge();
    }

}


import java.util.Comparator;
/**
 * This comparator compares two employees by their salaries.
 *
 */
public class EmployeeSalaryComparator implements Comparator {
    @Override
    public int compare(Employee emp1, Employee emp2) {
        return emp1.getSalary() - emp2.getSalary();
    }

}

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * This program demonstrates how to sort a list collection by multiple
 * attributes using a chained comparator.
 *
 *
 */
public class SortingMultipleAttributesExample {
    public static void main(String[] args) {
        System.out.println("===== SORTING BY MULTIPLE ATTRIBUTES =====");
        List listEmployees = new ArrayList();
        listEmployees.add(new Employee("Tom", "Developer", 45, 80000));
        listEmployees.add(new Employee("Sam", "Designer", 30, 75000));
        listEmployees.add(new Employee("Bob", "Designer", 45, 134000));
        listEmployees.add(new Employee("Peter", "Programmer", 25, 60000));
        listEmployees.add(new Employee("Tim", "Designer", 45, 130000));
        listEmployees.add(new Employee("Craig", "Programmer", 30, 52000));
        listEmployees.add(new Employee("Anne", "Programmer", 25, 51000));
        listEmployees.add(new Employee("Alex", "Designer", 30, 120000));
        listEmployees.add(new Employee("Bill", "Programmer", 22, 30000));
        listEmployees.add(new Employee("Samuel", "Developer", 28, 80000));
        listEmployees.add(new Employee("John", "Developer", 35, 67000));
        listEmployees.add(new Employee("Patrick", "Developer", 35, 140000));
        listEmployees.add(new Employee("Alice", "Programmer", 35, 80000));
        listEmployees.add(new Employee("David", "Developer", 35, 99000));
        listEmployees.add(new Employee("Jane", "Designer", 30, 82000));

        System.out.println("*** Before sorting:");
       for (Employee emp : listEmployees) {
            System.out.println(emp);
        }

        Collections.sort(listEmployees, new EmployeeChainedComparator(
                new EmployeeJobTitleComparator(),
                new EmployeeAgeComparator(),
                new EmployeeSalaryComparator())
        );

        System.out.println("\n*** After sorting:");

        for (Employee emp : listEmployees) {
            System.out.println(emp);
        }
    }

}


===== SORTING BY MULTIPLE ATTRIBUTES =====
*** Before sorting:
Tom     Developer   45  80000
Sam     Designer    30  75000
Bob     Designer    45  134000
Peter   Programmer  25  60000
Tim     Designer    45  130000
Craig   Programmer  30  52000
Anne    Programmer  25  51000
Alex    Designer    30  120000
Bill    Programmer  22  30000
Samuel  Developer   28  80000
John    Developer   35  67000
Patrick Developer   35  140000
Alice   Programmer  35  80000
David   Developer   35  99000
Jane    Designer    30  82000

*** After sorting:
Sam     Designer    30  75000
Jane    Designer    30  82000
Alex    Designer    30  120000
Tim     Designer    45  130000
Bob     Designer    45  134000
Samuel  Developer   28  80000
John    Developer   35  67000
David   Developer   35  99000
Patrick Developer   35  140000
Tom     Developer   45  80000
Bill    Programmer  22  30000
Anne    Programmer  25  51000
Peter   Programmer  25  60000
Craig   Programmer  30  52000

Alice   Programmer  35  80000

import java.util.Comparator;
import org.apache.commons.lang3.builder.CompareToBuilder;
 /**
 * This comparator sorts a list of Employees by job title, age and salary
 * into ascending order.
 *
 */
public class EmployeeComparator implements Comparator {
     @Override
    public int compare(Employee o1, Employee o2) {
        return new CompareToBuilder()
                .append(o1.getJobTitle(), o2.getJobTitle())
                .append(o1.getAge(), o2.getAge())
                .append(o1.getSalary(), o2.getSalary()).toComparison();
    }

}

Collections.sort(listEmployees, new EmployeeComparator())

No comments:

Post a Comment

உப்பு மாங்காய்

சுருக்குப்பை கிழவி. சுருக்கங்கள் சூழ் கிழவி. பார்க்கும் போதெல்லாம் கூடையுடனே குடியிருப்பாள். கூடை நிறைய குட்டி குட்டி மாங்காய்கள். வெட்டிக்க...