Sorting using Comparator in java with example
Tags: collection, java, collections, collectionsinjava
Published: 2020-11-16 17:53:18

<hr />

<strong>Table of Contents</strong>

<nav>
<ul class="ez-toc-list ez-toc-list-level-1">
 	<li><a title="Basic points about Comparator interface." href="#Basic_points_about_Comparator_interface">Basic points about Comparator interface.</a></li>
 	<li><a title="Example of sorting using Comparator in java using anonymous class." href="#Example_of_sorting_using_Comparator_in_java_using_anonymous_class">Example of sorting using Comparator in java using anonymous class.</a></li>
 	<li><a class="ez-toc-link ez-toc-heading-3" title="Example of sorting using Comparator in java implementing Comparator interface." href="#Example_of_sorting_using_Comparator_in_java_implementing_Comparator_interface">Example of sorting using Comparator in java implementing Comparator interface.</a></li>
 	<li><a title="Example of Sorting using Comparator and Java 8." href="#Example_of_Sorting_using_Comparator_and_Java_8">Example of Sorting using Comparator and Java 8.</a></li>
 	<li><a title="Soring list of an object using Comparator.comparing()." href="#Soring_list_of_an_object_using_Comparator_comparing()">Soring list of an object using Comparator.comparing().</a></li>
</ul>
<h2 id="Basic_points_about_Comparator_interface">Basic points about Comparator interface.</h2>
Comparator is an interface available in java.util package, which provides multiple sorting(means we can sort the basis of id and name at the same time).

The <strong>Comparator</strong> <strong>interface</strong> contains <strong>compare(Object o1, Object o2)</strong> method which we can override and keep sorting logic there.

For sorting using <strong>Comparator</strong> interface <strong>we need to use Collections.sort(List list, Comparator c)</strong> method.
<h3><strong>Different ways of sorting using Comparator interface.</strong></h3>
<h4>Override compare() method.</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">@Override public int compare(Object o1, Object o2) {
 Employee e1 = (Employee) o1;
 Employee e2 = (Employee) o2;
 return e1.getName().compareTo(e2.getName());
}</pre>
<h4>Using Java 8 lambda expression.</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">Collections.sort(employeeList, (employee1, employee2) -&gt; employee1.getName().compareTo(employee2.getName()));</pre>
<h4>Using Comparator.comparing().</h4>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">employeeList.sort(Comparator.comparing(Employee::getId));</pre>
&nbsp;
<h2 id="Example_of_sorting_using_Comparator_in_java_using_anonymous_class">Example of sorting using Comparator in java using anonymous class.</h2>
In this example, we are going to sort Employee type of list on the basis of the name without implementing Comparator(Employee class will not implement Comparator).
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.util.Collections;
import java.util.*;
class Employee {
 private String name;
 private int id;
 public Employee() {}
 public Employee(String name, int id) {
  super();
  this.name = name;
  this.id = id;
 }
 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;
 }
}
===============================================================
public class SortingUsingComparator {
 public static void main(String[] args) throws Exception {
  List emplist = new ArrayList &lt; &gt; ();
  emplist.add(new Employee("mohan", 5));
  emplist.add(new Employee("radhika", 1));
  emplist.add(new Employee("gopi", 3));
  emplist.add(new Employee("krishna", 2));
  System.out.println("sorting using comparator by name ------");
  Collections.sort(emplist, new Comparator() {
   @Override public int compare(Object o1, Object o2) {
    Employee e1 = (Employee) o1;
    Employee e2 = (Employee) o2;
    return e1.getName().compareTo(e2.getName());
   }
  });
  for (Employee e: emplist) {
   System.out.println(e.getId() + " " + e.getName());
  }
  System.out.println("sorting using comparator by id --------");
  Collections.sort(emplist, new Comparator() {
   @Override public int compare(Object o1, Object o2) {
    Employee e1 = (Employee) o1;
    Employee e2 = (Employee) o2;
    return e1.getId() - e2.getId();
   }
  });
  for (Employee e: emplist) {
   System.out.println(e.getId() + " " + e.getName());
  }
 }
}</pre>
</nav>
<blockquote><strong>sorting using comparator by name ——</strong>
<pre>3 gopi
2 krishna
5 mohan
1 radhika
</pre>
<strong>sorting using comparator by id ——–</strong>
<pre>1 radhika
2 krishna
3 gopi
5 mohan
</pre>
</blockquote>
<h2 id="Example_of_sorting_using_Comparator_in_java_implementing_Comparator_interface">Example of sorting using Comparator in java implementing Comparator interface.</h2>
we can define a separate class which will implement Comparator interface.
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.util.*;
import java.io.*;
class Employee {
 String name;
 int id;
 Employee(String name, int id) {
  this.name = name;
  this.id = id;
 }
}
class NameComparator implements Comparator {
 @Override public int compare(Object o1, Object o2) {
  Employee e1 = (Employee) o1;
  Employee e2 = (Employee) o2;
  return e1.name.compareTo(e2.name);
 }
}
class IdComparator implements Comparator {
 @Override public int compare(Object o1, Object o2) {
  Employee e1 = (Employee) o1;
  Employee e2 = (Employee) o2;
  return e2.id - e1.id;
 }
}
public class SortByUsingComparator {
 public static void main(String[] args) {
  List emplist = new ArrayList();
  emplist.add(new Employee("rakesh", 105));
  emplist.add(new Employee("bittu", 103));
  emplist.add(new Employee("tituu", 110));
  emplist.add(new Employee("asharaf", 108));
  System.out.println("sorting by name-------");
  Collections.sort(emplist, new NameComparator());
  Iterator itr = emplist.iterator();
  while (itr.hasNext()) {
   Employee emp = (Employee) itr.next();
   System.out.println(emp.name + " " + emp.id);
  }
  System.out.println("sorting by id---------");
  Collections.sort(emplist, new IdComparator());
  Iterator itr2 = emplist.iterator();
  while (itr2.hasNext()) {
   Employee emp = (Employee) itr2.next();
   System.out.println(emp.name + " " + emp.id);
  }
 }
}</pre>
<blockquote><strong>The output of the above program is –</strong>
<pre>anjali 108
bittu 103
rakesh 105
shibha 110
</pre>
<strong>sorting by id———</strong>
<pre>shibha 110
anjali 108
rakesh 105
bittu 103
</pre>
</blockquote>
<h2 id="Example_of_Sorting_using_Comparator_and_Java_8">Example of Sorting using Comparator and Java 8.</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class Employee {
 private String name;
 private int id;
 Employee(String name, int id) {
  this.name = name;
  this.id = id;
 }
 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;
 }
}
public class SortingUsingJava8 {
 public static void main(String[] args) {
  List employeeList = new ArrayList();
  employeeList.add(new Employee("rakesh", 105));
  employeeList.add(new Employee("bittu", 103));
  employeeList.add(new Employee("shibha", 110));
  employeeList.add(new Employee("anjali", 108));
  System.out.println("sorting on basis of name-------");
  Collections.sort(employeeList, (employee1, employee2) -&gt; employee1.getName().compareTo(employee2.getName()));// Lambda expression for sorting on basis of name
  for (Employee employee: employeeList) {
   System.out.println(employee.getName() + " " + employee.getId());
  }
  Lambda expression
  for sorting on basis of id System.out.println("sorting on basis of id-------");
  Collections.sort(employeeList, (employee1, employee2) -&gt; employee1.getId() - employee2.getId());// Lambda expression for sorting on basis of id
  for (Employee employee: employeeList) {
   System.out.println(employee.getName() + " " + employee.getId());
  }
 }
}</pre>

<blockquote>
<pre>The output of above program.

</pre>
<strong>Sorting on basis of name——-</strong>
<pre>anjali 108
bittu 103
rakesh 105
shibha 110

</pre>
<strong>Sorting on basis of id——-</strong>
<pre>bittu 103
rakesh 105
anjali 108
shibha 110
</pre>
</blockquote>
<h2 id="Soring_list_of_an_object_using_Comparator_comparing()">Soring list of an object using Comparator.comparing().</h2>
<pre class="EnlighterJSRAW" data-enlighter-language="generic">import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
class Employee {
 private String name;
 private int id;
 Employee(String name, int id) {
  this.name = name;
  this.id = id;
 }
 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;
 }
}
public class SortingUsingJava8 {
 public static void main(String[] args) {
  List employeeList = new ArrayList();
  employeeList.add(new Employee("rakesh", 105));
  employeeList.add(new Employee("bittu", 103));
  employeeList.add(new Employee("shibha", 110));
  employeeList.add(new Employee("anjali", 108));
  System.out.println("sorting on basis of name-------");
  employeeList.sort(Comparator.comparing(Employee::getName));
  for (Employee employee: employeeList) {
   System.out.println(employee.getName() + " " + employee.getId());
  }
  System.out.println("sorting on basis of id-------");
  employeeList.sort(Comparator.comparing(Employee::getId));
  for (Employee employee: employeeList) {
   System.out.println(employee.getName() + " " + employee.getId());
  }
 }
}</pre>
<pre>The output of the above program. Sorting on basis of name: anjali 108 bittu 103 rakesh 105 shibha 110 Sorting on basis of id: bittu 103 rakesh 105 anjali 108 shibha 110</pre>
</blockquote>
Learn more about<strong> <a href="https://onlinetutorials.tech/java-collection/">collection in java</a></strong>

<hr />