<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aakash Khurana on Medium]]></title>
        <description><![CDATA[Stories by Aakash Khurana on Medium]]></description>
        <link>https://medium.com/@aakashkhurana?source=rss-e563f650d8f0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Aakash Khurana on Medium</title>
            <link>https://medium.com/@aakashkhurana?source=rss-e563f650d8f0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 06:39:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aakashkhurana/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[✨ Java Object Comparison: Comparable vs. Comparator ✨]]></title>
            <link>https://medium.com/@aakashkhurana/java-object-comparison-comparable-vs-comparator-390fecb2fd55?source=rss-e563f650d8f0------2</link>
            <guid isPermaLink="false">https://medium.com/p/390fecb2fd55</guid>
            <category><![CDATA[java8]]></category>
            <category><![CDATA[comparable]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[comparator]]></category>
            <category><![CDATA[objects-in-java]]></category>
            <dc:creator><![CDATA[Aakash Khurana]]></dc:creator>
            <pubDate>Tue, 31 Oct 2023 15:42:09 GMT</pubDate>
            <atom:updated>2023-10-31T15:42:34.525Z</atom:updated>
            <content:encoded><![CDATA[<p>Both Comparator and Comparable are interfaces in Java used for comparing objects, but Comparable is an interface defining a strategy of comparing an object with other objects of the same type. This is called the class’s “natural ordering.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*Ln8-thf9cadb99-69N__wg.jpeg" /></figure><p>Suppose we have a Book class representing books in a library, with attributes like title, author, and publishYear. We want to sort a list of books based on their publish years in ascending order</p><p>public class Book implements Comparable&lt;Book&gt; {</p><p>private String title;</p><p>private String author;</p><p>private int publishYear;</p><p>private int price;</p><p><a href="http://twitter.com/Override">@Override</a></p><p>public int compareTo(Book otherBook) {</p><p>// Compare books based on their publish years</p><p>return Integer.compare(this.publishYear, otherBook.publishYear);</p><p>}</p><p>}</p><p>The Book class implements the Comparable&lt;Book&gt; interface, indicating that objects of the Book class can be compared with each other.</p><p>The compareTo method is overridden, comparing books based on their publishYear attribute.</p><p>A list of Book objects can be sorted using the Collections.sort() method without needing an external comparator.</p><p>Now, sorting a list of Book objects is as easy as calling Collections.sort(library). No fuss, just clean, natural sorting!</p><p>But what if we need diverse sorting strategies? This is where Comparator swoops in. Suppose we want to sort by publish year and price simultaneously. Creating custom comparators like BookPublishYearComparator and BookPriceComparator gives us the power to sort dynamically, without altering the Book class.</p><p>java</p><p>Copy code</p><p>public class BookPublishYearComparator implements Comparator&lt;Book&gt; {</p><p><a href="http://twitter.com/Override">@Override</a></p><p>public int compare(Book firstBook, Book secondBook) {</p><p>return Integer.compare(firstBook.getPublishYear(), secondBook.getPublishYear());</p><p>}</p><p>}</p><p>public class BookPriceComparator implements Comparator&lt;Book&gt; {</p><p><a href="http://twitter.com/Override">@Override</a></p><p>public int compare(Book firstBook, Book secondBook) {</p><p>return Double.compare(firstBook.getPrice(), secondBook.getPrice());</p><p>}</p><p>}</p><p>When to Use One Over the Other:</p><p>Use Comparable:</p><p>When you have a natural ordering for your objects that makes sense universally. For example, sorting strings alphabetically or sorting integers numerically.</p><p>When you have control over the class and can modify its code.</p><p>Use Comparator:</p><p>When you want to sort objects in multiple ways, depending on the context.</p><p>When you want to sort classes that you don’t have control over (e.g., third-party or Java library classes) without modifying their code.</p><p>When you want to sort objects based on different criteria without changing their original class implementation.</p><p>In summary, use Comparable when you want to define a default natural ordering for your objects, and use Comparator when you need to define multiple custom orderings or when you want to sort objects of classes that you don’t have control over.</p><p>Java 8 provides new ways of defining Comparators by using lambda expressions, and the comparing() static factory method.</p><p>// Using Lambda Expression for Comparing by Publish Year</p><p>Comparator&lt;Book&gt; byPublishYear = Comparator</p><p>.comparing(Book::getPublishYear);</p><p>// Using Lambda Expression for Comparing by Price</p><p>Comparator&lt;Book&gt; byPrice = Comparator</p><p>.comparing(Book::getPrice);</p><p>“Why use a Comparator when we have Comparable?</p><p>No Modification Access:</p><p>When we can’t change the original class, making it Comparable is not an option.</p><p>Avoiding Class Modification:</p><p>Using Comparators spares us from altering our existing classes.</p><p>Multiple Strategies:</p><p>Comparators enable diverse comparison methods, a flexibility not offered by Comparable.”</p><p>#JavaLearning #Comparator #Comparable #Java</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=390fecb2fd55" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>