How To Dissever Object Inwards Coffee - Comparator Too Comparable Example
Java Object Sorting Example
Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
Difference betwixt PATH in addition to Classpath inward Java
How produce y'all form a listing of Objects inward Java is 1 of the oft asked coding questions inward Java interviews in addition to surprisingly non every Java programmers know How sorting of object happens inward Java. Comparator in addition to Comparable interface along alongside Collections.sort() method are used to form the listing of object inward Java. compare() and compareTo() method of Comparator in addition to Comparable interface provides comparing logic needed for sorting objects. compareTo() method is used to render Object's natural club sorting in addition to compare() method is used to form Object alongside whatever arbitrary field. Almost all value classes inward Java library e.g. String, Integer, Double, BigDecimal implement compareTo() to specify their natural sorting order. While overriding compareTo method String is sorted lexicographically in addition to Integers are sorted numerically. Just beware that it must inconsistent alongside equals method i.e. ii objects which are equal past times equals method inward Java, compareTo() method must render nada for them. Anyway, sorting measure value Object is non a work for many Java programmer only unopen to of them actually create out when it comes to sorting custom Objects or domain Objects. In this Java sorting tutorial, nosotros volition create a custom object in addition to form listing of Object inward ascending in addition to descending order.
Sorting listing of Object inward ascending in addition to descending Order
Here is the listing of steps nosotros volition follow inward this Java sorting tutorial for creating custom Object, implementing Comparable or Comparator in addition to in conclusion sorting the listing of Object on ascending in addition to descending order. Our cognition of sorting ArrayList inward ascending in addition to descending order volition come upward handy here.
1) Create Order object every bit custom or domain object
2) Implement Comparable in addition to Comparator interface to define sorting logic
3) Sort listing of Object using Collections.sort method
package test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* Java plan to evidence Object sorting inward Java. This Java program
* evidence Comparable in addition to Comparator implementation provided past times Order
* shape past times sorting listing of Order object inward ascending in addition to descending order.
* Both inward natural club using Comparable in addition to custom Order using Comparator inward Java
*
* @author http://java67.blogspot.com
*/
public class ObjectSortingExample {
public static void main(String args[]) {
//Creating Order object to demonstrate Sorting of Object inward Java
Order ord1 = new Order(101,2000, "Sony");
Order ord2 = new Order(102,4000, "Hitachi");
Order ord3 = new Order(103,6000, "Philips");
//putting Objects into Collection to sort
List<Order> orders = new ArrayList<Order>();
orders.add(ord3);
orders.add(ord1);
orders.add(ord2);
//printing unsorted collection
System.out.println("Unsorted Collection : " + orders);
//Sorting Order Object on natural club - ascending
Collections.sort(orders);
//printing sorted collection
System.out.println("List of Order object sorted inward natural club : " + orders);
// Sorting object inward descending club inward Java
Collections.sort(orders, Collections.reverseOrder());
System.out.println("List of object sorted inward descending club : " + orders);
//Sorting object using Comparator inward Java
Collections.sort(orders, new Order.OrderByAmount());
System.out.println("List of Order object sorted using Comparator - total : " + orders);
// Comparator sorting Example - Sorting based on customer
Collections.sort(orders, new Order.OrderByCustomer());
System.out.println("Collection of Orders sorted using Comparator - past times client : " + orders);
}
}
/*
* Order shape is a domain object which implements
* Comparable interface to render sorting on the natural order.
* Order likewise provides twain of custom Comparators to
* form object based upon total in addition to customer
*/
class Order implements Comparable<Order> {
private int orderId;
private int amount;
private String customer;
/*
* Comparator implementation to Sort Order object based on Amount
*/
public static class OrderByAmount implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
return o1.amount > o2.amount ? 1 : (o1.amount < o2.amount ? -1 : 0);
}
}
/*
* Anohter implementation or Comparator interface to form listing of Order object
* based upon client name.
*/
public static class OrderByCustomer implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
return o1.customer.compareTo(o2.customer);
}
}
public Order(int orderId, int amount, String customer) {
this.orderId = orderId;
this.amount = amount;
this.customer = customer;
}
public int getAmount() {return amount; }
public void setAmount(int amount) {this.amount = amount;}
public String getCustomer() {return customer;}
public void setCustomer(String customer) {this.customer = customer;}
public int getOrderId() {return orderId;}
public void setOrderId(int orderId) {this.orderId = orderId;}
/*
* Sorting on orderId is natural sorting for Order.
*/
@Override
public int compareTo(Order o) {
return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
}
/*
* implementing toString method to impress orderId of Order
*/
@Override
public String toString(){
return String.valueOf(orderId);
}
}
Output
Unsorted Collection : [103, 101, 102]
List of Order object sorted inward natural club : [101, 102, 103]
List of object sorted inward descending club : [103, 102, 101]
List of Order object sorted using Comparator - total : [101, 102, 103]
Collection of Orders sorted using Comparator - past times client : [102, 103, 101]
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
*
* Java plan to evidence Object sorting inward Java. This Java program
* evidence Comparable in addition to Comparator implementation provided past times Order
* shape past times sorting listing of Order object inward ascending in addition to descending order.
* Both inward natural club using Comparable in addition to custom Order using Comparator inward Java
*
* @author http://java67.blogspot.com
*/
public class ObjectSortingExample {
public static void main(String args[]) {
//Creating Order object to demonstrate Sorting of Object inward Java
Order ord1 = new Order(101,2000, "Sony");
Order ord2 = new Order(102,4000, "Hitachi");
Order ord3 = new Order(103,6000, "Philips");
//putting Objects into Collection to sort
List<Order> orders = new ArrayList<Order>();
orders.add(ord3);
orders.add(ord1);
orders.add(ord2);
//printing unsorted collection
System.out.println("Unsorted Collection : " + orders);
//Sorting Order Object on natural club - ascending
Collections.sort(orders);
//printing sorted collection
System.out.println("List of Order object sorted inward natural club : " + orders);
// Sorting object inward descending club inward Java
Collections.sort(orders, Collections.reverseOrder());
System.out.println("List of object sorted inward descending club : " + orders);
//Sorting object using Comparator inward Java
Collections.sort(orders, new Order.OrderByAmount());
System.out.println("List of Order object sorted using Comparator - total : " + orders);
// Comparator sorting Example - Sorting based on customer
Collections.sort(orders, new Order.OrderByCustomer());
System.out.println("Collection of Orders sorted using Comparator - past times client : " + orders);
}
}
/*
* Order shape is a domain object which implements
* Comparable interface to render sorting on the natural order.
* Order likewise provides twain of custom Comparators to
* form object based upon total in addition to customer
*/
class Order implements Comparable<Order> {
private int orderId;
private int amount;
private String customer;
/*
* Comparator implementation to Sort Order object based on Amount
*/
public static class OrderByAmount implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
return o1.amount > o2.amount ? 1 : (o1.amount < o2.amount ? -1 : 0);
}
}
/*
* Anohter implementation or Comparator interface to form listing of Order object
* based upon client name.
*/
public static class OrderByCustomer implements Comparator<Order> {
@Override
public int compare(Order o1, Order o2) {
return o1.customer.compareTo(o2.customer);
}
}
public Order(int orderId, int amount, String customer) {
this.orderId = orderId;
this.amount = amount;
this.customer = customer;
}
public int getAmount() {return amount; }
public void setAmount(int amount) {this.amount = amount;}
public String getCustomer() {return customer;}
public void setCustomer(String customer) {this.customer = customer;}
public int getOrderId() {return orderId;}
public void setOrderId(int orderId) {this.orderId = orderId;}
/*
* Sorting on orderId is natural sorting for Order.
*/
@Override
public int compareTo(Order o) {
return this.orderId > o.orderId ? 1 : (this.orderId < o.orderId ? -1 : 0);
}
/*
* implementing toString method to impress orderId of Order
*/
@Override
public String toString(){
return String.valueOf(orderId);
}
}
Output
Unsorted Collection : [103, 101, 102]
List of Order object sorted inward natural club : [101, 102, 103]
List of object sorted inward descending club : [103, 102, 101]
List of Order object sorted using Comparator - total : [101, 102, 103]
Collection of Orders sorted using Comparator - past times client : [102, 103, 101]
Important points to note:
1) If y'all implement Comparable interface in addition to override compareTo() method it must last consistent alongside equals() method i.e. for equal object past times equals() method compareTo() must render zero. failing to in addition to then volition deport upon contract of SortedSet e.g. TreeSet in addition to SortedMap similar TreeMap, which uses compareTo() method for checking equality
2) Some programmer role Integer subtraction to implement compareTo() inward Java, which tin campaign overflow number if both integers are non positive. See How compareTo industrial plant inward Java for to a greater extent than details.
3) This instance of sorting Object inward Java likewise shows a skilful instance of Where to role nested static shape inward Java. In this instance We receive got created custom Comparator every bit a static inner shape So that they tin access properties of Order for comparing in addition to likewise they are exclusively used inward the context of Order class.
4) Don't forget to revise Difference betwixt Comparator in addition to Comparable inward Java, which is 1 of the close asked Java questions on Interviews.
5) Remember to role Collections.reverseOrder() comparator for sorting Object inward opposite club or descending order, every bit shown inward this example.
6) Use Generics patch implementing Comparator in addition to Comparable interface, that prevents mistake of accidentally overloading compareTo() in addition to compare() method instead of overriding it because both of these methods bring Object every bit a parameter. By using Generics in addition to @Override annotation nosotros effectively withdraw that subtle error.
7) This Object Sorting Example inward Java likewise teaches us Why y'all should override toString() inward Java. If y'all are going to shop your Object inward Collection similar List, Set or Map than printing Collection volition telephone band toString() method of each stored Object. By providing readable String format y'all tin run into What is stored inward a collection inward logs. This is likewise a useful logging tip inward Java.
That's all on How to form the listing of Object inward Java. It's upward to y'all whether to role Comparable or Comparator interface for implementing sorting logic inward Java.
Further Learning
Data Structures in addition to Algorithms: Deep Dive Using Java
Difference betwixt PATH in addition to Classpath inward Java
0 Response to "How To Dissever Object Inwards Coffee - Comparator Too Comparable Example"
Post a Comment