Sorting using Comparable in java with example
Tags: collection, java, collectionsinjava, comparable
Published: 2020-07-04 16:30:37

<div class="ez-toc-title-container">
<p class="ez-toc-title"><strong>Table of Contents</strong></p>
</div>
<nav>
<ul class="ez-toc-list ez-toc-list-level-1">
 	<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-1" title="Basic points about the comparable interface." href="#Basic_points_about_the_comparable_interface">Basic points about the comparable interface.</a></li>
 	<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-2" title="Program to sort on the basis of the name using Comparable." href="#Program_to_sort_on_the_basis_of_the_name_using_Comparable">Program to sort on the basis of the name using Comparable.</a></li>
 	<li class="ez-toc-page-1 ez-toc-heading-level-2"><a class="ez-toc-link ez-toc-heading-3" title="Program to sort on the basis of the id using Comparable." href="#Program_to_sort_on_the_basis_of_the_id_using_Comparable">Program to sort on the basis of the id using Comparable.</a></li>
</ul>
<h2 id="Basic_points_about_the_comparable_interface">Basic points about the comparable interface.</h2>
<a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html">Comparable</a> is an interface available in java.lang package, which provides single sorting(means we can sort either the basis of id or name at a time. Consider we have Employee class which contains fields name and id).

The Comparable interface <strong>contains compare()</strong> method. If we want to sort any collection of user-defined objects using comparable, our java class must need to implement Comparable interface and override <strong>compareTo(Object o)</strong> method.

</nav>
<h2 id="Program_to_sort_on_the_basis_of_the_name_using_Comparable">Program to sort on the basis of the name using Comparable.</h2>
<ul>
 	<li>Define an Employee class which should implement <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html">Comparable</a> interface and create two variables name and id.  Provide corresponding getter/setter and parameterized constructor. Here we are going to sort employee object on basis of Id.</li>
 	<li>Override compareTo () method and provide logic.</li>
 	<li>
<blockquote>
<pre>@Override
public int compareTo(Object o) {
        Employee employee = (Employee) o;
        String name = employee.name;
        return this.name.compareTo(name);
}
</pre>
</blockquote>
</li>
 	<li>Override compareTo () method and provide logic.</li>
 	<li>Create a couple of employee object using parameterized constructor and add into list.</li>
 	<li>
<blockquote>
<pre>List emplist = new ArrayList();
emplist.add(new Employee("John", 101));
emplist.add(new Employee("Eric", 106));
emplist.add(new Employee("Arya", 103));
emplist.add(new Employee("Sansa", 105));
emplist.add(new Employee("Cersei", 102));
</pre>
</blockquote>
</li>
 	<li>Use Collections.sort(emplist) the method which will internally call the compareTo() method(Check here how String compareTo() method internally works in java). Here Collections is a class and sort() is a static method. Use Java 8 forEach() method and print the name and id.</li>
</ul>
Comparable example in java:
<pre class="EnlighterJSRAW" data-enlighter-language="java">import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee implements Comparable {
 private String name;
 private int id;
 public Employee(String string, int i) {
  this.name = string;
  this.id = i;
 }
 public String getName() {
  return name;
 }
 public void setName(String name) {
  this.name = name;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 @Override 
 public int compareTo(Object o) {
  Employee employee = (Employee) o;
  String name = employee.name;
  return this.name.compareTo(name);
 }
}
public class SortingByNameUsingComprable {
 public static void main(String[] args) {
  List emplist = new ArrayList();
  emplist.add(new Employee("John", 101));
  emplist.add(new Employee("Eric", 106));
  emplist.add(new Employee("Arya", 103));
  emplist.add(new Employee("Sansa", 105));
  emplist.add(new Employee("Cersei", 102));
  Collections.sort(emplist);
  emplist.forEach(empolyee -&gt; 
          System.out.println(empolyee.getName() + " " + empolyee.getId()));
 }
}</pre>
<blockquote>
<pre>Arya 103
Cersei 102
Eric 106
John 101
Sansa 105
</pre>
</blockquote>
<h2 id="Program_to_sort_on_the_basis_of_the_id_using_Comparable">Program to sort on the basis of the id using Comparable.</h2>
For sorting on basis of id we need to change compareTo() logic as below. The rest of the steps would be the same.
<pre class="EnlighterJSRAW" data-enlighter-language="generic">@Override public int compareTo(Object o) {
 Employee employee = (Employee) o;
 return this.getId() - employee.getId();
}</pre>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.lang.reflect.Field;
import java.util.*;
 
class Employee implements Comparable {
    String name;
    int id;
 
    public Employee(String string, int i) {
        this.name = string;
        this.id = i;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    @Override
    public int compareTo(Object o) {
        Employee employee = (Employee) o;
        return this.getId() - employee.getId();
 
    }
}
 
public class SortingByIdUsingComprable {
    public static void main(String[] args) {
        List emplist = new ArrayList();
        emplist.add(new Employee("John", 101));
        emplist.add(new Employee("Eric", 106));
        emplist.add(new Employee("Arya", 103));
        emplist.add(new Employee("Sansa", 105));
        emplist.add(new Employee("Cersei", 102));
 
        Collections.sort(emplist);
        emplist.forEach(empolyee -&gt; System.out.println(empolyee.getName() + "   " + empolyee.getId()));
    }
}</pre>
<blockquote>
<pre>John 101
Cersei 102
Arya 103
Sansa 105
Eric 106
</pre>
</blockquote>
Learn more about<strong> <a href="https://onlinetutorials.tech/java-collection/">collection in java</a></strong>