{"id":1894,"date":"2016-10-12T15:25:25","date_gmt":"2016-10-12T15:25:25","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=1894"},"modified":"2017-03-30T16:51:06","modified_gmt":"2017-03-30T16:51:06","slug":"comparable-vs-comparator","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/comparable-vs-comparator\/","title":{"rendered":"Comparable vs Comparator"},"content":{"rendered":"<p><strong>Comparable<\/strong> is for objects with a natural ordering. The object itself knows how it is to be ordered.If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.<\/p>\n<p><strong>Comparator <\/strong> is for objects without a natural ordering or when you wish to use a different ordering.<\/p>\n<p><strong>Natural ordering<\/strong> is the Ordering implemented on the objects of each class. This ordering is referred to as the class&#8217;s natural ordering.For example Strings Natural Ordering is defined in String Class <\/p>\n<p><strong>Comparable<\/strong><br \/>\nCompares object of itself with some other objects.Comparable overrides <strong>compareTo<\/strong><\/p>\n<p><strong>Employee.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.acme.users;\r\n\r\npublic class Employee implements Comparable&lt;Employee&gt; {\r\n\tpublic String EmpName;\r\n\tpublic Integer EmpId;\r\n\tpublic Integer Age;\r\n\t\r\n\tpublic Employee(Integer pEmpId, String pEmpName, Integer pAge)\r\n\t{\r\n\t\tthis.EmpName = pEmpName;\r\n\t\tthis.EmpId   = pEmpId;\r\n\t\tthis.Age     = pAge;\r\n\t}\r\n\t\r\n\t\r\n\tpublic String getEmpName() {\r\n\t\treturn EmpName;\r\n\t}\r\n\tpublic void setEmpName(String empName) {\r\n\t\tEmpName = empName;\r\n\t}\r\n\tpublic Integer getEmpId() {\r\n\t\treturn EmpId;\r\n\t}\r\n\tpublic void setEmpId(Integer empId) {\r\n\t\tEmpId = empId;\r\n\t}\r\n\tpublic Integer getAge() {\r\n\t\treturn Age;\r\n\t}\r\n\tpublic void setAge(Integer age) {\r\n\t\tAge = age;\r\n\t}\r\n\t\r\n\t@Override\r\n\tpublic int compareTo(Employee arg0) \r\n\t{\t\r\n\t\tif(this.getEmpId() == arg0.getEmpId())\r\n\t\t\treturn 0;\r\n\t\telse if (this.getEmpId() &gt; arg0.getEmpId())\r\n\t\t\treturn 1;\r\n\t\telse\r\n\t\t\treturn -1;\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>EmpDashBoard.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.acme.users;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\n\r\npublic class EmpDashBoard {\r\n\tpublic static void main(String&#x5B;] args) {\r\n\r\n\t\tList&lt;Employee&gt; arrEmpList = new ArrayList();\r\n\r\n\t\tEmployee objEmp1 = new Employee(101, &quot;Ahmed&quot;, 31);\r\n\t\tEmployee objEmp2 = new Employee(127, &quot;Mahesh&quot;, 24);\r\n\t\tEmployee objEmp3 = new Employee(109, &quot;Viparna&quot;, 85);\r\n\t\tEmployee objEmp4 = new Employee(101, &quot;Abdul&quot;, 26);\r\n\t\tEmployee objEmp5 = new Employee(104, &quot;Muthu&quot;, 23);\r\n\t\tEmployee objEmp6 = new Employee(115, &quot;Monalisa&quot;, 25);\r\n\r\n\t\tarrEmpList.add(objEmp1);\r\n\r\n\t\tarrEmpList.add(objEmp2);\r\n\t\tarrEmpList.add(objEmp3);\r\n\t\tarrEmpList.add(objEmp4);\r\n\t\tarrEmpList.add(objEmp5);\r\n\t\tarrEmpList.add(objEmp6);\r\n\r\n\t\tSystem.out.println(&quot;Sorted based on Natural Sorting(Emp Id)&quot;);\r\n\t\tSystem.out.println(&quot;Before Sorting&quot;);\r\n\t\tdispListContent(arrEmpList);\r\n\t\t\r\n\t\tCollections.sort(arrEmpList);\r\n\t\t\r\n\t\tSystem.out.println(&quot;After Sorting&quot;);\r\n\t\tdispListContent(arrEmpList);\r\n\t}\r\n\r\n\tpublic static void dispListContent(List&lt;Employee&gt; parrEmployeeLst) {\r\n\t\tSystem.out.println(&quot; &quot;);\r\n\r\n\t\tSystem.out.println(&quot;EmpId&quot; + &quot; &quot; + &quot;EmpName&quot; + &quot;     &quot; + &quot;Age&quot;);\r\n\t\tSystem.out.println(&quot;---------------------------&quot;);\r\n\t\tfor (Employee object : parrEmployeeLst) {\r\n\t\t\tSystem.out.print(object.getEmpId() + &quot;   &quot;);\r\n\t\t\tSystem.out.print(object.getEmpName() + &quot;     &quot;);\r\n\t\t\tSystem.out.println(object.getAge() + &quot; &quot;);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nSorted based on Natural Sorting(Emp Id)\r\n\r\nBefore Sorting\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n101   Ahmed       31 \r\n127   Mahesh      24 \r\n109   Viparna     85 \r\n101   Abdul       26 \r\n104   Muthu       23 \r\n115   Monalisa    25 \r\n\r\nAfter Sorting\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n101   Ahmed       31 \r\n101   Abdul       26 \r\n104   Muthu       23 \r\n109   Viparna     85 \r\n115   Monalisa    25 \r\n127   Mahesh      24 \r\n<\/pre>\n<p><strong>Comparator<\/strong><br \/>\nIn some situations, you may not want to change a class and make it comparable. In such cases, Comparator can be used.Comparator overrides <strong>compare<\/strong><\/p>\n<p>Comparator provides a way for you to provide custom comparison logic for types that you have no control over.<\/p>\n<p>In the below Example I have Sorted the Employee class Objects based on <strong>Name(EmpNameComparator)<\/strong>, <strong>Age(EmpAgeComparator)<\/strong> and based on <strong>EmpIDName(EmpIdNameComparator)<\/strong><\/p>\n<p><strong>EmpDashBoard.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.acme.users;\r\n\r\nimport java.util.ArrayList;\r\nimport java.util.Collections;\r\nimport java.util.List;\r\n\r\npublic class EmpDashBoard {\r\n\tpublic static void main(String&#x5B;] args) {\r\n\r\n\t\tList&lt;Employee&gt; arrEmpList = new ArrayList();\r\n\r\n\t\tEmployee objEmp1 = new Employee(101, &quot;Ahmed&quot;, 31);\r\n\t\tEmployee objEmp2 = new Employee(127, &quot;Mahesh&quot;, 24);\r\n\t\tEmployee objEmp3 = new Employee(109, &quot;Viparna&quot;, 85);\r\n\t\tEmployee objEmp4 = new Employee(101, &quot;Abdul&quot;, 26);\r\n\t\tEmployee objEmp5 = new Employee(104, &quot;Muthu&quot;, 23);\r\n\t\tEmployee objEmp6 = new Employee(115, &quot;Monalisa&quot;, 25);\r\n\r\n\t\tarrEmpList.add(objEmp1);\r\n\r\n\t\tarrEmpList.add(objEmp2);\r\n\t\tarrEmpList.add(objEmp3);\r\n\t\tarrEmpList.add(objEmp4);\r\n\t\tarrEmpList.add(objEmp5);\r\n\t\tarrEmpList.add(objEmp6);\r\n\r\n\t\tSystem.out.println(&quot;Sorted based on Natural Sorting(Emp Id)&quot;);\r\n\r\n\t\tSystem.out.println(&quot;Before Sorting&quot;);\r\n\t\tdispListContent(arrEmpList);\r\n\r\n\t\tSystem.out.println(&quot;Sorting based on Emp Name&quot;);\r\n\t\tCollections.sort(arrEmpList, new EmpNameComparator());\r\n\t\tdispListContent(arrEmpList);\r\n\r\n\t\tSystem.out.println(&quot;Sorting based on Emp Age&quot;);\r\n\t\tCollections.sort(arrEmpList, new EmpAgeComparator());\r\n\t\tdispListContent(arrEmpList);\r\n\r\n\t\tSystem.out.println(&quot;Sorting based on EmpId and Name&quot;);\r\n\t\tCollections.sort(arrEmpList, new EmpIdNameComparator());\r\n\t\tdispListContent(arrEmpList);\r\n\t}\r\n\r\n\tpublic static void dispListContent(List&lt;Employee&gt; parrEmployeeLst) {\r\n\t\tSystem.out.println(&quot; &quot;);\r\n\r\n\t\tSystem.out.println(&quot;EmpId&quot; + &quot; &quot; + &quot;EmpName&quot; + &quot;     &quot; + &quot;Age&quot;);\r\n\t\tSystem.out.println(&quot;---------------------------&quot;);\r\n\t\tfor (Employee object : parrEmployeeLst) {\r\n\t\t\tSystem.out.print(object.getEmpId() + &quot;   &quot;);\r\n\t\t\tSystem.out.print(object.getEmpName() + &quot;     &quot;);\r\n\t\t\tSystem.out.println(object.getAge() + &quot; &quot;);\r\n\t\t}\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>EmpNameComparator.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class EmpNameComparator implements Comparator&lt;Employee&gt;{\r\n\r\n\t@Override\r\n\tpublic int compare(Employee o1, Employee o2) {\r\n\t\tString a = o1.getEmpName();\r\n\t\tString b = o2.getEmpName();\r\n\t\t\r\n\t\t\/\/Strings Natural Order Comparable Method\r\n\t\tint compare = a.compareTo(b);\r\n\t\t\r\n\t\tif (compare &gt; 0){\r\n\t\t    return 1;\r\n\t\t}\r\n\t\telse if (compare &lt; 0) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>EmpAgeComparator.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class EmpAgeComparator  implements Comparator&lt;Employee&gt; {\r\n\t\r\n\t@Override\r\n\tpublic int compare(Employee o1, Employee o2) {\r\n\t\tInteger a = o1.getAge();\r\n\t\tInteger b = o2.getAge();\r\n\t\t\r\n\t\tif (a &gt; b){\r\n\t\t    return 1;\r\n\t\t}\r\n\t\telse if (a &lt; b) {\r\n\t\t\treturn -1;\r\n\t\t}\r\n\t\telse {\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n}\r\n<\/pre>\n<p><strong>EmpIdNameComparator.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class EmpIdNameComparator  implements Comparator&lt;Employee&gt;{\r\n\t\r\n\t@Override\r\n\tpublic int compare(Employee o1, Employee o2) {\r\n\t\tString a = o1.getEmpName();\r\n\t\tString b = o2.getEmpName();\r\n\t\t\r\n\t\t\r\n\t\tint i = Integer.compare(o1.getEmpId(), o2.getEmpId());\r\n\t\tif (i != 0) return i;\r\n\r\n\t    return a.compareTo(b);\r\n\t}\r\n\t\r\n}\r\n<\/pre>\n<p><strong>Output<\/strong><\/p>\n<pre>\r\nBefore Sorting\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n101   Ahmed      31 \r\n127   Mahesh     24 \r\n109   Viparna    85 \r\n101   Abdul      26 \r\n104   Muthu      23 \r\n115   Monalisa   25 \r\n\r\nSorting based on Emp Name\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n101   Abdul      26 \r\n101   Ahmed      31 \r\n127   Mahesh     24 \r\n115   Monalisa   25 \r\n104   Muthu      23 \r\n109   Viparna    85 \r\n\r\nSorting based on Emp Age\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n104   Muthu       23 \r\n127   Mahesh      24 \r\n115   Monalisa    25 \r\n101   Abdul       26 \r\n101   Ahmed       31 \r\n109   Viparna     85 \r\n\r\nSorting based on EmpId and Name\r\n \r\nEmpId EmpName     Age\r\n---------------------------\r\n101   Abdul       26 \r\n101   Ahmed       31 \r\n104   Muthu       23 \r\n109   Viparna     85 \r\n115   Monalisa    25 \r\n127   Mahesh      24 \r\n<\/pre>\n<p><strong><br \/>\ncomparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.<\/strong><\/p>\n<p>If there is a natural or default way of sorting Object already exist during development of Class than use Comparable. This is intuitive and you given the class name people should be able to guess it correctly like Strings are sorted chronically, Employee can be sorted by there Id etc. On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. for example Employee can again be sorted on name, salary or department and clients needs an API to do that. Comparator implementation can sort out this problem.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined&hellip; <a href=\"https:\/\/codethataint.com\/blog\/comparable-vs-comparator\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[193],"tags":[],"class_list":["post-1894","post","type-post","status-publish","format-standard","hentry","category-interview-questions-java"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/1894","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=1894"}],"version-history":[{"count":18,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/1894\/revisions"}],"predecessor-version":[{"id":2122,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/1894\/revisions\/2122"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=1894"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=1894"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=1894"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}