Java util package provides us number of sorted data structures; one of those is the TreeSet. TreeSet is an implementation of Set and it stores the elements in sorted order. All elements needs to be added into a TreeSet should implement Comparable interface directly or indirectly or the TreeSet should be constructed with an appropriate Comparator. Since you are implementing the Comparable interface you are forced to implement the compareTo method. Normally the compareTo method is used to write most obvious/natural comparison logic for given object. In the below given example I have used the employeeId to compare two employees.
If you want to use a different attribute other than what is written in the compareTo method then you will have to write a Comparator for it. EmployeeNameComparator class is used to compare two employee instances using its name attribute. When you use a comparator you must pass that as the constructor argument for TreeSet.
The first example in the program sorts a collection of String using the sorted data structure TreeSet. Since the String implementation is comparable, elements are sorted in the natural order. In the second example the user defined class Employee is sorted using the TreeSet, this time the compareTo method is the Employee class is being called every time when you add an element into TreeSet to determine its position. In the third example a Comparator is being used to sort the employees based on their name. In the fourth example DepartmentName comparator is being used to sort the department objects. The last example throws an exception saying that the elements are not comparable. You can see that the Department class is not comparable since it’s not implementing the Comparable interface. In that case, we should have supplied a Comparator to the TreeSet to sort its elements.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 |
package com.ourownjava.corejava.util; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; /** * @date 21st June, 2011 * @author ourownjava.com * * Example program to demonstrate the use of comparable and comparator. * Use of Comparator with SortedSet Comparable and SortedSet * */ public class ComparatorExample { public static void main(final String args[]) { final ComparatorExample example = new ComparatorExample(); example.sortString(); example.sortEmployee(); example.sortEmployee(new EmployeeNameComparator()); example.sortDepartment(new DepartmentNameComparator()); example.sortDepartment(); } private void sortString() { System.out.println("ComparatorExample.sortedString()"); final Set<String> sortedSet = new TreeSet<String>(); sortedSet.add("India"); sortedSet.add("United States"); sortedSet.add("England"); sortedSet.add("Singapore"); for (final String str : sortedSet) { System.out.println(str); ; } } private void sortEmployee() { System.out.println("ComparatorExample.sortEmployee()"); final Set<Employee> sortedSet = new TreeSet<Employee>(); final Employee emp1 = new Employee(); emp1.setEmployeeId(1L); emp1.setFirstName("Sara"); emp1.setLastName("Thomas"); final Employee emp2 = new Employee(); emp2.setEmployeeId(2L); emp2.setFirstName("Sen"); emp2.setLastName("Varghese"); final Employee emp3 = new Employee(); emp3.setEmployeeId(3L); emp3.setFirstName("Saran"); emp3.setLastName("Joseph"); sortedSet.add(emp3); sortedSet.add(emp1); sortedSet.add(emp2); for (final Employee employee : sortedSet) { System.out.println(employee); } } private void sortEmployee(final Comparator<Employee> comparator) { System.out.println("ComparatorExample.sortEmployee(Comparator)"); final Set<Employee> sortedSet = new TreeSet<Employee>(comparator); final Employee emp1 = new Employee(); emp1.setEmployeeId(1L); emp1.setFirstName("Sara"); emp1.setLastName("Thomas"); final Employee emp2 = new Employee(); emp2.setEmployeeId(2L); emp2.setFirstName("Sara"); emp2.setLastName("Varghese"); final Employee emp3 = new Employee(); emp3.setEmployeeId(3L); emp3.setFirstName("Saran"); emp3.setLastName("Joseph"); final Employee emp4 = new Employee(); emp4.setEmployeeId(4L); emp4.setFirstName("Paul"); emp4.setLastName("Alexander"); sortedSet.add(emp3); sortedSet.add(emp1); sortedSet.add(emp4); sortedSet.add(emp2); for (final Employee employee : sortedSet) { System.out.println(employee); } } private void sortDepartment() { System.out.println("ComparatorExample.sortDepartment()"); final Set<Department> sortedSet = new TreeSet<Department>(); final Department dep1 = new Department(); dep1.setDepartmentId(1L); dep1.setName("Technology"); sortedSet.add(dep1); final Department dep2 = new Department(); dep2.setDepartmentId(2L); dep2.setName("Operations"); sortedSet.add(dep2); final Department dep3 = new Department(); dep3.setDepartmentId(3L); dep3.setName("Security"); sortedSet.add(dep3); final Department dep4 = new Department(); dep4.setDepartmentId(4L); dep4.setName("Human Resources"); sortedSet.add(dep4); for (final Department department : sortedSet) { System.out.println(department.toString()); } } private void sortDepartment(Comparator<Department> comparator) { System.out.println("ComparatorExample.sortDepartment(Comparator)"); final Set<Department> sortedSet = new TreeSet<Department>(comparator); final Department dep1 = new Department(); dep1.setDepartmentId(1L); dep1.setName("Technology"); sortedSet.add(dep1); final Department dep2 = new Department(); dep2.setDepartmentId(2L); dep2.setName("Operations"); sortedSet.add(dep2); final Department dep3 = new Department(); dep3.setDepartmentId(3L); dep3.setName("Security"); sortedSet.add(dep3); final Department dep4 = new Department(); dep4.setDepartmentId(4L); dep4.setName("Human Resources"); sortedSet.add(dep4); for (final Department department : sortedSet) { System.out.println(department.toString()); } } } class Employee implements Comparable<Employee> { Long employeeId; String firstName; String lastName; public void setEmployeeId(final Long employeeId) { this.employeeId = employeeId; } public void setFirstName(final String firstName) { this.firstName = firstName; } public void setLastName(final String lastName) { this.lastName = lastName; } public String getName() { final StringBuilder builder = new StringBuilder(); builder.append(this.firstName); builder.append(" "); builder.append(this.lastName); return builder.toString(); } public int compareTo(Employee o) { return this.employeeId.compareTo(o.employeeId); } @Override public String toString() { return "Employee [employeeId=" + employeeId + ", firstName=" + firstName + ", lastName=" + lastName + "]"; } } class Department { Long departmentId; String name; public void setDepartmentId(final Long departmentId) { this.departmentId = departmentId; } public void setName(final String name) { this.name = name; } public String getName() { return this.name; } @Override public String toString() { return "Department [departmentId=" + departmentId + ", name=" + name + "]"; } } class EmployeeNameComparator implements Comparator<Employee> { public int compare(Employee o1, Employee o2) { return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } } class DepartmentNameComparator implements Comparator<Department> { public int compare(Department o1, Department o2) { return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase()); } } |
Console Output.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
/home/mnt/java com.ourownjava.corejava.util.ComparatorExample ComparatorExample.sortedString() England India Singapore United States ComparatorExample.sortEmployee() Employee [employeeId=1, firstName=Sara, lastName=Thomas] Employee [employeeId=2, firstName=Sen, lastName=Varghese] Employee [employeeId=3, firstName=Saran, lastName=Joseph] ComparatorExample.sortEmployee(Comparator) Employee [employeeId=4, firstName=Paul, lastName=Alexander] Employee [employeeId=1, firstName=Sara, lastName=Thomas] Employee [employeeId=2, firstName=Sara, lastName=Varghese] Employee [employeeId=3, firstName=Saran, lastName=Joseph] Department [departmentId=4, name=Human Resources] Department [departmentId=2, name=Operations] Department [departmentId=3, name=Security] Department [departmentId=1, name=Technology] Exception in thread "main" java.lang.ClassCastException: org.sanju.Department cannot be cast to java.lang.Comparable at java.util.TreeMap.put(Unknown Source) at java.util.TreeSet.add(Unknown Source) at org.sanju.ComparatorExample.sortDepartment(ComparatorExample.java:115) at org.sanju.ComparatorExample.main(ComparatorExample.java:25) |
Pingback: Comparable VS Comparator in Java | Clean Java