Here is the list of steps we will follow in this Java sorting tutorial for creating custom Object, implementing Comparable or Comparator, and finally sorting the list of Object in ascending and descending order.
1) Create Order object as custom or domain object
3) Sort list of Object using Collections.sort methodBy the way, after Java 8, using Comparator and Comparable has been even easier. You can lambda expression and method reference to create more clear and concise code for Comparator. It improves both readability and reusability. You can see these Java 8 courses to learn more about those features.
And, here is our complete Java program to demonstrate how to use Comparato rand Comparator to define the order for objects and how to sort them in both natural and custom order.import java.util.ArrayList;
/**
*
* Java program to test Object sorting in Java. This Java program
* test Comparable and Comparator implementation provided by Order
* class by sorting list of Order objects in ascending and descending order.
* Both in natural order using Comparable and custom Order using Comparator in Java
*
* @author http://java67.blogspot.com
*/
public static void main(String args[]) {
//Creating Order object to demonstrate Sorting of Object in Java
//putting Objects into Collection to sort
//printing unsorted collection
//Sorting Order Object on natural order - ascending
//printing sorted collection
// Sorting object in descending order in Java
//Sorting object using Comparator in Java
// Comparator sorting Example - Sorting based on customer
/*
* Order class is a domain object which implements
* Comparable interface to provide sorting on the natural order.
* Order also provides a couple of custom Comparators to
* sort object based upon amount and customer
*/
private int orderId;
/*
* Comparator implementation to Sort Order object based on Amount
*/
@Override
/*
* Another implementation or Comparator interface
* to sort the list of the Order object
* based upon customer name.
*/
@Override
public Order(int orderId, int amount, String customer) {
public int getAmount() {return amount; }
public String getCustomer() {return customer;}
public int getOrderId() {return orderId;}
/*
* Sorting on orderId is natural sorting for Order.
*/
/*
* implementing toString method to print orderId of Order
*/
Output
That's all on How to sort the list of Objects in Java. It's up to you whether to use the Comparable or Comparator interface for implementing sorting logic in Java.
Other Java Interview Questions you may find good
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4