×

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

Java Math.multiplyExact() method in Java

Java has an inbuilt math function called Math.multiplyExact() that returns the sum of the parameters. If the result exceeds an integer, an exception is thrown. There is no need to...

2 minutes read.

Frugal number in Java

A frugal number is a positive integer with base b that has more digits than the number of prime factors it can be factored into (including exponents greater than 1)....

3 minutes read.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.

Duodecimal in Java

Duodecimal is a notation style in which a number with a base of 12 is referred to be a duodecimal number. In Java, we can use to convert duodecimal integers...

2 minutes read.

Java URL Class with Example

Java URL Uniform Resource Locator To find any resource on the internet, you need to have an address of it. The URL and IP addresses are the pointers used for this purpose....

12 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

Print Pencil Shape Pattern in Java

Another pattern made from asterisk symbols that use loops and other logical concepts is the pencil pattern. It is usually requested to draw a pattern using a program. To write the...

6 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Java Queue

The Java.util package has the interface Queue, which does extend the Collection interface. It is used to protect the parts that are managed using the FIFO approach. Being an interface, the...

5 minutes read.

Check if the given array is mirror inverse in Java

The primary objective is to check whether the given array is mirror inverse or not. The values and position of the specified array are switched, and a duplicate array is created....

3 minutes read.

Java Integer longValue() method

The longValue()  method of Java Integer class returns a long value for this Integer after a widening primitive conversion. Syntax public long longValue() Parameters NA Specified by This method is specified by longValue in class Number Return...

1 minute read.

Switch Case with Enum in Java

From some conditions, the java switch statement executes one statement. Similar to the If-Else-If ladder statement, this can be Byte, short, int, long, enum, string, and some wrapper types like...

4 minutes read.

Java Math hypot() Method

The hypot() method of Math class returns the square root for the expression x2 + y2 without the intermediate underflow or overflow . Syntax: public static double hypot(double x, double y) Parameters: The parameters...

2 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java Boolean logicalAnd() Method

The logicalAnd() method of Java Boolean class returns the result of implementing logicalAND operation on the specified Boolean operands. Syntax:public static boolean logicalAnd (boolean a, boolean b) Parameters:The parameters ‘a’ and ‘b’...

2 minutes read.

How to set path in Java

To make programs that can run on our systems, we need to install programming language-related software in our systems. Different programming languages require different types of software, aka IDEs (Integrated Development...

5 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Star Pattern Programs in Java

Star Pattern Programs in Java The star pattern programs in Java is the part of pattern programs in Java, which we discussed earlier. Right Triangle Star Pattern Filename: StarPatternExample.java public class StarPatternExample {              public static void...

4 minutes read.

Anagram Program in Java using String

Anagram Program in Java Anagrams are those words that are generated by rearrangement of the letters of another phrase or word. Usually, while doing the rearrangement, the original letters are used...

8 minutes read.

How to Iterate a HashMap in Java?

Hash-map is a class of Java collections framework which has the functionality to implement the Map interface of Java. It stores the data in key-value pairs and can be accessed...

5 minutes read.