Java Program to Sort Objects in ArrayList by Date
Last Updated :
21 Feb, 2022
The foremost tool that strikes is the sort() method to be used for the comparator mechanism of the Collections class which sorts in the decreasing order. Yes if in generic we want to achieve the goal considering the boundary condition where objects to sorted are user-defined then blindly do with Comparator. Both approaches are discussed below where the object is also created of the user-defined type.
Methods:
In Java, we have multiple methods to sort objects in ArrayList by Date. This can be done by using the Comparable<> interface or by the Collections.sort() method, to accomplish this task you can use any one of them.
- Using Comparator interface
- Using Collections.sort() method
Now let's discuss all of them one by one.
Method 1: Using Comparator interface
The Java Comparator interface is used to order the objects of the user-defined class. By using the Comparator<> interface you can sort the elements on the basis of any data member defined in the user-defined class. The java.util package contains this interface. We can do this task by using methods compare() and compareTo() which will be used for comparing the objects of our DateItem class.
Approach:
- Create a new class and name that class as DateItem and create a variable of type String, then create a constructor of class DateItem and pass that String type variable here.
- In the main method create an ArrayList of type DateItem.
- Store the objects of DateItem in the ArrayList.
- Create another class called sortItems which implements Comparator and pass our DateItem class to a comparator.
- Now in the Comparator class create a compare method that returns an integer and takes two parameters of the 'DateItem' object as compare(Object obj1, Object obj2).
- Inside the compare method for return value use the compareTo() method which will return the specified value by comparing the DateItem objects.
- Now in the main method use Collections.sort() method and pass the ArrayList and 'SortItem' class object to it, it will sort the dates, and output will be generated.
Example 1
Java
// Java Program to Sort Objects in ArrayList by Date
// Using Comparator interface
// Importing required classes
import java.util.*;
// Class 1
// helper class for DateItem
class DateItem {
// Member variable of this class
String date;
// Constructor of this class
DateItem(String date)
{
// This keyword refers to current object itself
this.date = date;
}
}
// Class 2
// Helper class implementing Comparator
// from the Comparable interface
class sortItems implements Comparator<DateItem> {
// Method of this class
// @Override
public int compare(DateItem a, DateItem b)
{
// Returning the value after comparing the objects
// this will sort the data in Ascending order
return a.date.compareTo(b.date);
}
}
// Class 3
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating ArrayList class object
// Declaring object of type-DateItem
// class(user-defined)
ArrayList<DateItem> dateList = new ArrayList<>();
// Adding data to the ArrayList
// using standard add() method
dateList.add(new DateItem("2020-03-25"));
dateList.add(new DateItem("2019-01-27"));
dateList.add(new DateItem("1998-01-27"));
dateList.add(new DateItem("1998-02-26"));
// Sorting the ArrayList
// using Collections.sort() method
Collections.sort(dateList, new sortItems());
// Display message
System.out.println("Sorted in Ascending Order");
// Iterating the list using for-each loop
for (DateItem d : dateList) {
// Printing the sorted items from the List
System.out.println(d.date);
}
}
}
OutputSorted in Ascending Order
1998-01-27
1998-02-26
2019-01-27
2020-03-25
Note : This code will sort the dates in Ascending order. If you want to change the order of sorting you can refer to the program below:
Example 2
Java
// Java Program to Sort Objects in ArrayList by Date
// Using Comparator interface
// Importing required classes
import java.util.*;
// Class 1
// Helper class
class DateItem {
// Member variable
String date;
// Constructor of this class
DateItem(String date)
{
// this keyword refers to current instance itself
this.date = date;
}
}
// Class 2
// Helper class implementing Comparable interface
class sortItems implements Comparator<DateItem> {
// @Override
// Method of this class
// To compare datetime objects
public int compare(DateItem a, DateItem b)
{
// Returning the value after comparing the objects
// this will sort the data in Descending order
return b.date.compareTo(a.date);
}
}
// Class 3
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Creating an ArrayList of DateItem class
// (user-defined)
ArrayList<DateItem> dateList = new ArrayList<>();
// Adding data to the ArrayList
// using standard add() method
dateList.add(new DateItem("2020-03-25"));
dateList.add(new DateItem("2019-01-27"));
dateList.add(new DateItem("1998-01-27"));
dateList.add(new DateItem("1998-02-26"));
// Sorting the elements on ArrayList object above
Collections.sort(dateList, new sortItems());
// Display message only
System.out.println("Sorted in Descending Order");
// Iterating the List
// using for-each loop
for (DateItem d : dateList) {
// Printing the sorted items from the List
System.out.println(d.date);
}
}
}
OutputSorted in Descending Order
2020-03-25
2019-01-27
1998-02-26
1998-01-27
Method 2: Using Collections.sort() method
The Collections.sort() method can be used to sort the ArrayList of custom objects. We can use this method to sort the Objects in ArrayList by the Date. java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collections in ascending order. It works similar to java.util.Arrays.sort() method, but it is better than it as it can sort the elements of Array as well as a linked list, queue, and many more presents in it.
Example
Java
// Java Program to Sort Objects in ArrayList by Date
// Using Collections.sort() method
// Importing required classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an ArrayList of String to
// store the Dates
ArrayList<String> datesList = new ArrayList<>();
// Adding date to ArrayList
// using standard add() method
datesList.add("2020-03-25");
datesList.add("2019-01-27");
datesList.add("2020-03-26");
datesList.add("2020-02-26");
// Display message only
System.out.println(
"Dates Object before sorting : ");
// Iterating in the ArrayList
// using for each loop
for (String dates : datesList) {
// Printing the data from the list
System.out.println(dates);
}
// Sorting the ArrayList
// using Collections.sort() method
Collections.sort(datesList);
// Display message only
System.out.println("Dates Object after sorting : ");
// Iterating in the ArrayList
// using for-each loop
for (String dates : datesList) {
// Printing the data from the list
System.out.println(dates);
}
}
}
OutputDates Object before sorting :
2020-03-25
2019-01-27
2020-03-26
2020-02-26
Dates Object after sorting :
2019-01-27
2020-02-26
2020-03-25
2020-03-26
Similar Reads
How to Sort an ArrayList of Objects by Property in Java?
ArrayList in Java (equivalent to vector in C++) having a dynamic size. It can be shrinked or expanded based on size. ArrayList is a part of the collection framework and is present in java.util package. --> java.util Package --> ArrayList Class Syntax: Creating an empty ArrayList ArrayList <
7 min read
Java Program to Sort ArrayList of Custom Objects By Property
Here we are going to look at the approach of sorting an ArrayList of custom objects by using a property. Approach: 1. Create a getter function which returns the value stored in the class variable. 2. Create a list and use sort() function which takes the values of the list as arguments and compares t
2 min read
Java Program to Sort Names in an Alphabetical Order
For, sorting names in an Alphabetical order there are multiple ways to sort the array, like using inbuilt Arrays.sort() method or using normal sorting algorithms like the bubble sort, merge sort. Here let's use the bubble sort and inbuilt sort. Example: Input : Array[] = {"Sourabh", "Anoop, "Harsh",
3 min read
Java Program to Sort a HashMap by Keys and Values
HashMap<K, V> is a Java Collection and is a part of java.util package. It provides the basic implementation of the Map interface of Java. It stores the data in the form of Key, Value pairs, where the keys must be unique but there is no restriction for values. If we try to insert the duplicate
3 min read
Java Program for Menu Driven Sorting of Array
In Java, sorting an array consists of arranging the elements in a particular order, such as ascending or descending. This can be achieved using various algorithms like Bubble Sort, Selection Sort, or Insertion Sort. A menu-driven program allows users to select the desired sorting method dynamically.
7 min read
Java Program to Sort the Elements of an Array in Ascending Order
Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort()
2 min read
How Objects Can an ArrayList Hold in Java?
ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java just as Vector in C++. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. In order to understan
3 min read
Java Program to Sort the Elements of an Array in Descending Order
Here, we will sort the array in descending order to arrange elements from largest to smallest. The simple solution is to use Collections.reverseOrder() method. Another way is sorting in ascending order and reversing.1. Using Collections.reverseOrder()In this example, we will use Collections.reverseO
2 min read
Java Program to Sort Items By Weight
Given two array items and weights which denotes items and their respective weights. Both arrays are of equal length. For every index 'i', items[i] and weights[i] represent the ith item name and its weight respectively. Your task is to return a new array of items sorted in decreasing order by their w
3 min read
How to Convert an ArrayList of Objects to a JSON Array in Java?
In Java, an ArrayList is a resizable array implementation of the List interface. It implements the List interface and is the most commonly used implementation of List. In this article, we will learn how to convert an ArrayList of objects to a JSON array in Java. Steps to Convert an ArrayList of Obje
3 min read