<div dir="ltr" style="text-align: justify;">
<p>In this tutorial, it shows the use of<i> java.lang.Comparable </i>and<i> java.util.Comparator </i>to sort a Java object based on its property value. Java provides some inbuilt methods to sort primitive types array or Wrapper classes array or list. Here we will first learn how we can sort an array/list of primitive types and wrapper classes and then we will use java.lang.Comparable and java.util.Comparator interfaces to sort array/list of custom classes.</p>
<h2><b>Difference between comparable and comparator in java</b></h2>
<p>In Java, the element in collections can be sorted by using <i>TreeSet </i>or <i>TreeMap</i>. To sort the data elements a class needs to implement Comparator or Comparable interface. That&#8217;s why all Wrapper classes like Integer, Double and String class implements the Comparable interface.</p>
<p>A class implementing Comparable interface need to override<i> compareTo(Object obj) </i>method and put the logic for sorting.</p>
<h3><i>The method returns an int value: -1,0,1</i><br />
<i></i></h3>
<ul>
<li><i>It will return -1: If this object is lesser than the passed object</i></li>
<li><i>It will return 0: If this object is same the passed object</i><br />
<i></i></li>
<li><i>It will return 1: If this object is greater than the passed object</i></li>
</ul>
<div id="ads-id" align="center"></div>
<p><b>Consider a class Person.</b></p>
<pre class="highlight">class Person { 
public String name; 
public String lastName; 
 
public Person(String name, String lastName){ 
 this.name=name; 
 this.lastName=lastName; 
} 
public String getName(){ 
return name; 
} 
public String getLastName(){ 
return lastName; 
} 
 
public static void main(String arg[]){ 
 List myList = new ArrayList(); 
 myList.add(new Person("Robert","USA")); 
 myList.add(new Person("Andy","UK")); 
 myList.add(new Person("Harish","India")); 
 for(Person person : myList){ 
 System.out.println("My name is "+person.getName()); 
 } 
} 
 
} 
</pre>
<p><b>Output is :</b><br />
<i>My name is Robert</i><br />
<i>My name is Andy</i><br />
<i>My name is Harish</i></p>
<p>But now I want that the objects to be sorted on name basis should be retrieved in sorted order. Consider a class Person.</p>
<pre class="highlight">class Person implements Comparable{ 
public String name; 
public String lastName; 
 
public Person(String name, String lastName){ 
 this.name=name; 
 this.lastName=lastName; 
} 
public String getName(){ 
 return name; 
} 
public String getLastName(){ 
 return lastName; 
} 
 
public int compareTo(Person p){ 
 return this.name.compareTo(p.getName); 
} 
public static void main(String arg[]){ 
 List myList = new ArrayList(); 
 myList.add(new Person("Robert","USA")); 
 myList.add(new Person("Andy","UK")); 
 myList.add(new Person("Harish","India")); 
 Collections.sort(myList); 
 for(Person person : myList){ 
 System.out.println("My name is "+person.getName()); 
 } 
} 
} 
</pre>
<p><b>Output is :</b><br />
<i>My name is Andy</i><br />
<i>My name is Harish</i><br />
<i>My name is Robert</i></p>
<p><b>A couple of things which needs to be taken into consideration:</b></p>
<ul style="text-align: left;">
<li>Collections.sort() will sort only the collection having objects which implements either one of the comparing interfaces.</li>
<li>Collections.sort() will sort the same list.</li>
</ul>
<h2><b>Comparator interface </b></h2>
<p>It is used when extra logic is required to sort the objects. One need to override compare(Object obj1, Object obj2) method. For example, you want the list of Person object to be sorted on the basis of complete name i.e &#8220;name lastName&#8221; but also, on the other hand, doesn&#8217;t want to change the Person class-default sorting implementation or Person class is a jar so so no code modification in it can be done. First, create a Custom Comparator.</p>
<pre class="highlight">public class MyCustomComparator implements Comparator{ 
 public int compare(Object obj1, Object obj2){ 
 Person p1 =(Person) obj1; 
 Person p2 =(Person) ob2; 
 String p1Name = p1.getName()+ " " +p1.getLastName(); 
 String p2Name = p2.getName()+ " " +p2.getLastName(); 
 return p1Name.toCompareTo(p2Name); 
 } 
} 
// Changes made in main method of Person class. 
public static void main(String arg[]){ 
 List myList = new ArrayList(); 
 myList.add(new Person("Robert","USA")); 
 myList.add(new Person("Robert","UK")); 
 myList.add(new Person("Robert","India")); 
 Collections.sort(myList new MyCustomComparator()); 
 for(Person person : myList){ 
 System.out.println("My name is "+person.getName() + " " + person.getLastName()); 
 } 
} 
</pre>
<p><b>OutPut:</b><br />
<i>My name is Robert India</i><br />
<i>My name is Robert UK</i><br />
<i>My name is Robert USA</i></p>
<h3><b>A couple of things which needs to be taken into consideration:</b></h3>
<p>1) For Comparator interface, you need to override method compare(obj)<br />
2) In collections.sort() the instance of Comparator need to be passed. In this example, the list is sorted according to the custom Comparator created.</p>
<p><b>Refrences-</b><br />
http://java-questions.com/</p>
<p> ;</p>
</div>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/serialization-in-java/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/classnotfoundexception-vs/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '189'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…