Sunday 7 October 2018


                                      Comparable And Comparator Concept in java?




Comparable and Comparator in Java are very useful for sorting collection of objects. 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.Comparableand java.util.Comparator interfaces to sort array/list of custom classes.


ava provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods, you can check any Wrapper, String or Date class to confirm this. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.


But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Java Comparator interface because Comparable.compareTo(Object o)method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.

Java Comparator

Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.





package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListTest {
public static void main(String[] args) {
ArrayList<Integer> al=new ArrayList<>();
al.add(10);
al.add(4);
al.add(6);
al.add(3);
al.add(50);
System.out.println("before sorting");
for(int i:al)//autoboxing
{
System.out.println(i);
}

System.out.println("after sorting");
Collections.sort(al);
for(int i:al)//autoboxing
{
System.out.println(i);
}

}



}


o/p:------------------------------------------------

before sorting
10
4
6
3
50
after sorting
3
4
6
10
50


==========================================================================================================================================

package govind;

public class Product {

String pname;
int price;
public Product(String pname,int price) {
super();
this.pname = pname;
this.price = price;
}
@Override
public String toString() {
return "Product [pname=" + pname + ", price=" + price + "]";
}




}



package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ProductList {
public static void main(String[] args) {

ArrayList<Product> productList=new ArrayList<>();
productList.add(new Product("laptop", 45000));
productList.add(new Product("Desktop", 25000));
productList.add(new Product("T.v", 15000));
productList.add(new Product("Mobile", 10000));
productList.add(new Product("Jeans", 1500));
productList.add(new Product("Shirt", 1000));
System.out.println(productList);
//Collections.sort(productList);//error





}

}



o/p:-----------------------


compile time error
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Product>)

at govind.ProductList.main(ProductList.java:17)
=========================================================================================================================================

Comparable Concept:-------


package govind;

public class ProductComparable implements Comparable<ProductComparable> {

private String pname;
private int Price;
public ProductComparable(String pname, int price) {
super();
this.pname = pname;
Price = price;
}

@Override
public String toString() {
return "ProductComparable [pname=" + pname + ", Price=" + Price + "]";
}



   // if u want to sort on the basis of price
   //@Override
public int compareTo(ProductComparable pricecompare) {
if(Price>pricecompare.Price)
{
return 1;
    }
else if(Price<pricecompare.Price)
{
return -1;
}
else
{
return 0;
}

}



/*if u want to sort on the basis of pname:

@Override
public int compareTo(ProductComparable productName) {

return pname.compareTo(productName.pname);
}*/



}




package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ProductComparableMain {

public static void main(String[] args) {
ArrayList<ProductComparable> productList=new ArrayList<>();
productList.add(new ProductComparable("Laptop", 45000));
productList.add(new ProductComparable("Desktop", 25000));
productList.add(new ProductComparable("T.v", 15000));
productList.add(new ProductComparable("Mobile", 10000));
productList.add(new ProductComparable("Jeans", 1500));
productList.add(new ProductComparable("Shirt", 1000));
System.out.println("Before Sorting");
System.out.println(productList);
System.out.println("After Sorting on the basis of price");
Collections.sort(productList);
System.out.println(productList);
}

}



o/p:-----------------------------------

Before Sorting
[ProductComparable [pname=Laptop, Price=45000], ProductComparable [pname=Desktop, Price=25000], ProductComparable [pname=T.v, Price=15000], ProductComparable [pname=Mobile, Price=10000], ProductComparable [pname=Jeans, Price=1500], ProductComparable [pname=Shirt, Price=1000]]
After Sorting on the basis of price
[ProductComparable [pname=Shirt, Price=1000], ProductComparable [pname=Jeans, Price=1500], ProductComparable [pname=Mobile, Price=10000], ProductComparable [pname=T.v, Price=15000], ProductComparable [pname=Desktop, Price=25000], ProductComparable [pname=Laptop, Price=45000]]



=============================================================================================================================================


Comparator Concept in java:--------------------

package govind;

public class Product {

String pname;
int price;
public Product(String pname,int price) {
super();
this.pname = pname;
this.price = price;
}
@Override
public String toString() {
return "Product [pname=" + pname + ", price=" + price + "]";
}




}




package govind;

import java.util.Comparator;

public class ProductNameComparator implements Comparator<Product>{

@Override
public int compare(Product p1, Product p2) {
return p1.pname.compareTo(p2.pname);
}





}



package govind;

import java.util.Comparator;

public class ProductPriceComparator  implements Comparator<Product>{

@Override
public int compare(Product p1, Product p2) {

return p1.price-p2.price;
}

}



package govind;

import java.util.ArrayList;
import java.util.Collections;

public class ProductListComparator {


public static void main(String[] args) {

ArrayList<Product> productList=new ArrayList<>();
productList.add(new Product("laptop", 45000));
productList.add(new Product("Desktop", 25000));
productList.add(new Product("T.v", 15000));
productList.add(new Product("Mobile", 10000));
productList.add(new Product("Jeans", 1500));
productList.add(new Product("Shirt", 1000));
System.out.println("************ Sorting on the basis of product name****************");
System.out.println("before sorting");
System.out.println(productList);
System.out.println("after sorting");
Collections.sort(productList,new ProductNameComparator());
System.out.println(productList);

System.out.println("************ Sorting on the basis of price****************");
System.out.println("before sorting");
System.out.println(productList);
System.out.println("after sorting");
Collections.sort(productList,new ProductPriceComparator());
System.out.println(productList);
}
}


o/p:----------------------------------------------------------------------------------

************ Sorting on the basis of product name****************
before sorting
[Product [pname=laptop, price=45000], Product [pname=Desktop, price=25000], Product [pname=T.v, price=15000], Product [pname=Mobile, price=10000], Product [pname=Jeans, price=1500], Product [pname=Shirt, price=1000]]
after sorting
[Product [pname=Desktop, price=25000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=Shirt, price=1000], Product [pname=T.v, price=15000], Product [pname=laptop, price=45000]]
************ Sorting on the basis of price****************
before sorting
[Product [pname=Desktop, price=25000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=Shirt, price=1000], Product [pname=T.v, price=15000], Product [pname=laptop, price=45000]]
after sorting
[Product [pname=Shirt, price=1000], Product [pname=Jeans, price=1500], Product [pname=Mobile, price=10000], Product [pname=T.v, price=15000], Product [pname=Desktop, price=25000], Product [pname=laptop, price=45000]]

No comments:

Post a Comment