Saturday, November 9, 2019

How To Course Of Written Report Object Inwards Coffee - Comparator Too Comparable Example

Java Object Sorting Example
How do y'all kind a listing of Objects inwards Java is 1 of the often asked coding questions inwards Java interviews together with surprisingly non every Java programmers know How sorting of object happens inwards Java. Comparator together with Comparable interface along alongside Collections.sort() method are used to kind the listing of object inwards Java. compare() and compareTo() method of Comparator together with Comparable interface provides comparing logic needed for sorting objects. compareTo() method is used to supply Object's natural guild sorting together with compare() method is used to kind Object alongside whatsoever arbitrary field. Almost all value classes inwards Java library e.g. String, Integer, Double, BigDecimal implement compareTo() to specify their natural sorting order. While overriding compareTo method String is sorted lexicographically together with Integers are sorted numerically. Just beware that it must inconsistent alongside equals method i.e. 2 objects which are equal yesteryear equals method inwards Java, compareTo() method must render nada for them.  Anyway,  sorting criterion value Object is non a employment for many Java programmer precisely around of them actually scrap when it comes to sorting custom Objects or domain Objects. In this Java sorting tutorial, nosotros volition do a custom object together with kind listing of Object inwards ascending together with descending order.



Sorting listing of Object inwards ascending together with descending Order

Here is the listing of steps nosotros volition follow inwards this Java sorting tutorial for creating custom Object, implementing Comparable or Comparator together with lastly sorting the listing of Object on ascending together with descending order. Our cognition of sorting ArrayList inwards ascending together with descending order volition come upward handy here.

1) Create Order object equally custom or domain object
2) Implement Comparable together with Comparator interface to define sorting logic
3) Sort listing of Object using Collections.sort method




How do y'all kind a listing of Objects inwards Java is 1 of the often asked  How to kind Object inwards Java - Comparator together with Comparable Examplepackage test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 *
 * Java programme to evidence Object sorting inwards Java. This Java program
 * evidence Comparable together with Comparator implementation provided yesteryear Order
 * course of teaching yesteryear sorting listing of Order object inwards ascending together with descending order.
 * Both inwards natural guild using Comparable together with custom Order using Comparator inwards Java
 *
 * @author http://java67.blogspot.com
 */

public class ObjectSortingExample {

    public static void main(String args[]) {
     
        //Creating Order object to demonstrate Sorting of Object inwards 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 guild - ascending
        Collections.sort(orders);
     
        //printing sorted collection
        System.out.println("List of Order object sorted inwards natural guild : " + orders);
     
        // Sorting object inwards descending guild inwards Java
        Collections.sort(orders, Collections.reverseOrder());
        System.out.println("List of object sorted inwards descending guild : " + orders);
             
        //Sorting object using Comparator inwards Java
        Collections.sort(orders, new Order.OrderByAmount());
        System.out.println("List of Order object sorted using Comparator - sum : " + orders);
     
        // Comparator sorting Example - Sorting based on customer
        Collections.sort(orders, new Order.OrderByCustomer());
        System.out.println("Collection of Orders sorted using Comparator - yesteryear client : " + orders);
    }
}

/*
 * Order course of teaching is a domain object which implements
 * Comparable interface to supply sorting on the natural order.
 * Order too provides brace of custom Comparators to
 * kind object based upon sum together with 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 kind 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 inwards natural guild : [101, 102, 103]
List of object sorted inwards descending guild : [103, 102, 101]
List of Order object sorted using Comparator - sum : [101, 102, 103]
Collection of Orders sorted using Comparator - yesteryear client : [102, 103, 101]


Important points to note:

1) If y'all implement Comparable interface together with override compareTo() method it must live consistent alongside equals() method i.e. for equal object yesteryear equals() method compareTo() must render zero. failing to together with thus volition impact contract of SortedSet e.g. TreeSet together with SortedMap similar TreeMap, which uses compareTo() method for checking equality

2) Some programmer role Integer subtraction to implement compareTo() inwards Java, which tin drive overflow number if both integers are non positive. See How compareTo industrial plant inwards Java for to a greater extent than details.

3) This instance of sorting Object inwards Java too shows a practiced instance of Where to role nested static course of teaching inwards Java. In this instance We receive got created custom Comparator equally a static inner course of teaching So that they tin access properties of Order for comparing together with too they are alone used inwards the context of Order class.

4) Don't forget to revise Difference betwixt Comparator together with Comparable inwards Java, which is 1 of the close asked Java questions on Interviews.

5) Remember to role Collections.reverseOrder() comparator for sorting Object inwards contrary guild or descending order, equally shown inwards this example.

6) Use Generics piece implementing Comparator together with Comparable interface, that prevents mistake of accidentally overloading compareTo() together with compare() method instead of overriding it because both of these methods receive got Object equally a parameter. By using Generics together with @Override annotation nosotros effectively take that subtle error.

7) This Object Sorting Example inwards Java too teaches us Why y'all should override toString() inwards Java. If y'all are going to shop your Object inwards Collection similar List, Set or Map than printing Collection volition telephone phone toString() method of each stored Object. By providing readable String format y'all tin meet What is stored inwards a collection inwards logs. This is too a useful logging tip inwards Java.

That's all on How to kind the listing of Object inwards Java. It's upward to y'all whether to role Comparable or Comparator interface for implementing sorting logic inwards Java.

Further Learning
Data Structures together with Algorithms: Deep Dive Using Java
Difference betwixt PATH together with Classpath inwards Java

No comments:

Post a Comment