Let's say we have an Employee Object with the fields as given below.
class Employee implements Comparable { private int empid; private String deptname; private String name; private float salary; public int getEmpid() { return empid; } public String getDeptname() { return deptname; } public String getName() { return name; } public float getSalary() { return salary; } public Employee(int empid, String deptname, String name, float salary) { this.empid = empid; this.deptname = deptname; this.name = name; this.salary = salary; } @Override public String toString() { return "Employee{" + "empid=" + empid + ", deptname=" + deptname + ", name=" + name + ", salary=" + salary + '}' + "\n"; } @Override public int hashCode() { int hash = 3; hash = 23 * hash + this.empid; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Employee other = (Employee) obj; if (this.empid != other.empid) { return false; } return true; } @Override public int compareTo(Object o) { if (o instanceof Employee) { Employee other = (Employee) o; return this.name.compareTo(other.name); } else { throw new RuntimeException("Comparison object is not matching"); } } }Requirement: We want to sort Employee objects first by deptname and then followed by employee name within each department.
public class MultipleSort { public static void main(String[] args) { Listemplist = new ArrayList (); emplist.add(new Employee(353744, "MCA", "Athiruban", 47000)); emplist.add(new Employee(311344, "CSE", "Nandhini", 41000)); emplist.add(new Employee(351144, "EEE", "Kishore", 44400)); emplist.add(new Employee(353321, "MCA", "Karthik", 37000)); emplist.add(new Employee(353711, "CSE", "Gopal", 37000)); emplist.add(new Employee(353743, "IT", "AthiNivas", 67000)); defaultSortandDisplay(emplist); sortByDeptAndThenByName(emplist); } private static void defaultSortandDisplay(List emplist) { Collections.sort(emplist); System.out.println("DefaultSortandDisplay->\n" + emplist); } private static void sortByDeptAndThenByName(List emplist) { Map > mapSortedByDept = new TreeMap >(); List finallist = new ArrayList (); for (Employee e : emplist) { if (mapSortedByDept.containsKey(e.getDeptname()) == true) { mapSortedByDept.get(e.getDeptname()).add(e); } else { List templist = new ArrayList (); templist.add(e); mapSortedByDept.put(e.getDeptname(), templist); } } System.out.println("Ordered by Department->\n" + mapSortedByDept); Collection > collectionSortedByDept = mapSortedByDept.values(); for (List indvlist : collectionSortedByDept) { Collections.sort(indvlist); finallist.addAll(indvlist); } System.out.println("Ordered by name within Department->\n" + mapSortedByDept); System.out.println("Final list->\n" + finallist); } }
No comments:
Post a Comment