×

Sort Dates in Java

The Collection class's sort() method, which is a component of the Comparator mechanism, arranges the data in decreasing order. The Comparator interface can be used to accomplish the goal while taking into account the boundary requirement that the components to be sorted were user-defined. The user-defined method is also processed to create the object in both of the methods that are detailed further below.

Java offers numerous options for sorting items in an ArrayList on date. Either the Comparable> interfaces or the Collections.sort() mechanism can be used to do it.

Any one of the following approaches are acceptable.

  • Comparator interface
  • Using sort() method                                           

Comparator Interface

The Java Comparator mechanism was required to sort the user-defined class's elements. You can order the elements using any instance variables declared inside the user-defined class by utilizing the Comparator> interface. This interface is part of the java.util package. We may perform this action by comparing the instances of our DateItem class through using methods compare() and compareTo().

Working Mechanism

  • Create a new class called DateItem, give it the type String, and give it a variable of that type. Then, create a function Object() { [native code] } for the DateItem class and pass the String type variable to it.
  • Establish an ArrayList of form DateItem in the main procedure.
  • Place the DateItem objects in the ArrayList.
  • Provide the DateItem class to a comparator and create a new class named sortItems that implements Comparator.
  • Create a compare method in the Comparator class now that accepts two inputs from the "DateItem" object and returns an integer (Object obj1, Object obj2).
  • Use the compareTo() function within the compare method to get the provided value as a return value by evaluating the DateItem objects.
  • Use Collections throughout the main method right now. The dates will be sorted using the sort() method when the ArrayList and 'SortItem' class object are passed to it.

Java programmes that use the Comparator interface to order the elements of an array list by date.

File name: Sortdates1.java

import java.util.*;  
class Datesort1  
{  
    String date;   
    
    Datesort1(String date)  
    {  
        // This keyword  leveraged  to refer current class object   
        this.date = date;  
    }  
}  
class sortCompare implements Comparator<Datessort1>   
{  
    // Method of this class  
    @Override  
    public int compare(Datesort1 a, Datesort1 b)  
    {  
        // Returns the data in ascending order which is already sorted   
        return a.date.compareTo(b.date);  
    }  
}  
public class SortDates1   
{  
    // code of the driver
    public static void main(String args[])  
    {  
        ArrayList<Datesort1> d = new ArrayList<>();  
       //appending data into the arraylist  
        d.add(new Datesort1("1978-12-22"));  
        d.add(new Datesort1("2006-10-04"));  
        d.add(new Datesort1("1981-07-28"));  
        d.add(new Datesort1("2001-08-16"));  
        // Sorting the arraylist using Collections.sort() method 
        Collections.sort(d, new sortCompare());  
        System.out.println("Dates which are sorted in Ascending order");  
        for (Datesort1 f: d)   
        {  
            System.out.println(f.d);  
        }  
    }  
}  

Output:

Dates which are sorted in Ascending order
1978-12-22
1981-08-28
2001-08-16
2006-10-04

File name: Sortdates2.java

import java.util.*;  
class Datesort2 
{  
    String date;  
    Datesort2(String date)  
    {  
        // This keyword leveraged to refer current class object   
        this.date = date;  
    }  
}  
class sortCompare implements Comparator<Datesort2>   
{  
    @Override  
    // Method of this class  
    public int compare(Datesort2 a, Datesort2 b)  
    {  
        /* Returns sorted data in Descending order */  
        return b.date.compareTo(a.date);  
    }  
}  
public class Sortdates2 {    
    public static void main(String args[])  
    {  
        ArrayList<Datesort2> d = new ArrayList<>();  
       //appending data into the arraylist  
        dates.add(new DateI("1978-12-22"));  
        dates.add(new DateI("2006-10-04"));  
        dates.add(new DateI("1981-07-28"));  
        dates.add(new DateI("2001-08-16"));  
        // Sorting the arraylist using Collections.sort() method 
        Collections.sort(dates, new sortCompare());  
        System.out.println("Dates which are sorted in Descending Order");  
      
        for (Datesort2 f : d)   
        {  
            System.out.println(f.d);  
        }  
    }  
}  

Output

Dates which are sorted in Descending Order
2006-10-04
2001-08-16
1981-07-28
1978-12-22

Using sort() Method

The ArrayList of customized objects can be sorted using the Collections.sort() method. The java.util.Collections class contains the java.util.Collections.sort()function that can be employed to arrange items inside an array list according to date. The elements in the supplied list of Collections are sorted in ascending order using this method. It functions similarly to the java.util.Arrays.sort() methods, but it is superior because it can sort both the elements of an array and any associated linked list, queue, and other objects.

Java program that use collections to order ArrayList's items by date.sort() technique.

File name: Sortdates3.java

import java.util.*;  
public class Sortdates3   
{  
   
    public static void main(String[] args)  
    {  
        // Initializing an ArrayList of String for stroring the dates
        ArrayList<String> dl = new ArrayList<>();  
        // Appending date to ArrayList by standard add() method   
        dl.add("1978-12-22");  
        dl.add("2006-10-04");  
        dl.add("1981-07-28");  
        dl.add("2001-08-16");  
        // Display message only  
        System.out.println("Dates before sorting : ");  
        for (String dates : datesList) {  
            // Printing the data from the list  
            System.out.println(dates);  
        }  
        //The ArrayList is sorted by Collections.sort() method   
        Collections.sort(datesList);  
        // Displays only messages 
        System.out.println( "Dates after sorting : ");  
        for(String dates : datesList) {  
            // Displaying  data from  list   
            System.out.println(dates);  
        }  
    }  
}  

Output:

Dates before sorting: 
1978-12-22  
2006-10-04  
1981-07-28  
2001-08-16  


Dates after sorting:
1978-12-22
1981-07-28
2001-08-16
2006-10-04

Related Topics

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Java Boolean parseBoolean() Method

The parseBoolean() method of Boolean class returns a Boolean value for the specified String argument. It returns true if and only if string’s value is equal to “true”, else it...

1 minute read.

Matrix Multiplication in Java

In Java, using the binary operator (*) we can perform matrix multiplication. A Matrix is a group of arrays. In the multiplication of matrices, the elements of each row are...

3 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Different Ways to Take Input from User in Java

Any information provided to a system for use is known as user input. Any responsive software or application must include user input. In Java, there are 4 different ways to...

5 minutes read.

Bad Operand types for Binary Operator Java

We will discuss how to handle issues in bad operand types for binary operator &, bad operand types for binary operator &&, bad operand types for binary operator ==, and...

4 minutes read.

Loose Coupling in Java

Loosely coupling mechanism in java means one reference of a variable capable of holding multiple implementation class memory is called loosely coupling. Or in other words, one interface reference variable...

3 minutes read.

Java Thread Lifecycle: States and Stages

Multithreading Multithreading is one of the most important features in object-oriented programming, and this multithreading can be implemented by various object-oriented programming languages like Java, Python, and C++. A multithreaded process...

7 minutes read.

Vigesimal in Java

A number system with a base of 20 is known as the vigesimal in Java. A base-20 (base-score) numeric system, often known as a vigesimal system, is centered on the twenty...

4 minutes read.

Converting Roman to Integer Numerals in java

In this article, you will be acknowledged about the process of conversion of roman numbers to integers in java. The most important approaches are discussed and also the implementation of...

3 minutes read.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

Java 9 Try With Resources

Java 9 provides the improvement in the try statement. It allows us to declare a try statement with duly declared resources. Whenever the user does not require the functionality with...

3 minutes read.

Static Array in Java

In this tutorial, we will study static arrays in Java. An array is a data structure that is of great importance in any programming language. It is classified into two...

3 minutes read.

Uses of Java

Java is used in many real-world Java applications, including technologies and tools. This Java programming language has become the backbone for developing many applications. In areas like embedded systems and...

3 minutes read.

Java Serialization

JAVA SERIALIZATION Serialization is a process by which objects can be represented as a sequence of bytes. These bytes have information about object's data, object's type and datatypes of members in...

3 minutes read.

Java File Input Stream

Java makes use of stream ideas to speed up input and output processes. All packages of input and output streams are contained in java.io.package. Stream: A stream is nothing more...

5 minutes read.

Menu Driven Program in Java

Menu Driven Program in Java The menu-driven program in Java is a program that displays a menu and then takes input from the user to choose an option from the displayed...

3 minutes read.

Difference between Abstract Class and Interface

There is a similarity between abstract class and interface is that we cannot create objects for both of them. But irrespective of this, there are some differences between them, let’s...

2 minutes read.

Class memory in Java

Anything specifically defined in the Java code is stored either inside the heap or the stack, which is particularly significant. Stack and heap are the two kinds of memory available...

6 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.