Sort objects in ArrayList by date?
You can make your object comparable:
public static class MyObject implements Comparable<MyObject> {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
return getDateTime().compareTo(o.getDateTime());
}
}
And then you sort it by calling:
Collections.sort(myList);
However sometimes you don't want to change your model, like when you want to sort on several different properties. In that case, you can create comparator on the fly:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
However, the above works only if you're certain that dateTime is not null at the time of comparison. It's wise to handle null as well to avoid NullPointerExceptions:
public static class MyObject implements Comparable<MyObject> {
private Date dateTime;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date datetime) {
this.dateTime = datetime;
}
@Override
public int compareTo(MyObject o) {
if (getDateTime() == null || o.getDateTime() == null)
return 0;
return getDateTime().compareTo(o.getDateTime());
}
}
Or in the second example:
Collections.sort(myList, new Comparator<MyObject>() {
public int compare(MyObject o1, MyObject o2) {
if (o1.getDateTime() == null || o2.getDateTime() == null)
return 0;
return o1.getDateTime().compareTo(o2.getDateTime());
}
});
Sorting list of objects by date property
You can use Collections.sort with a Comparator. In Java 8 with Lambdas it looks like this:
Collections.sort(list, (x, y) -> x.startDate.compareTo(y.startDate));
for (int i = 0; i < (list.size() - 1); i++) {
list.get(i).endDate = list.get(i + 1).startDate;
}
How to Sort Date in a Custom Arraylist in Android Studio?
You can use below method to sort your list by date.
Collections.sort(list, (item1, item2) -> {
Date date1 = stringToDate(item1.getDate());
Date date2 = stringToDate(item2.getDate());
if (date1 != null && date2 != null) {
boolean b1;
boolean b2;
if (isAscending) {
b1 = date2.after(date1);
b2 = date2.before(date1);
}else {
b1 = date1.after(date2);
b2 = date1.before(date2);
}
if (b1 != b2) {
if (b1) {
return -1;
}
if (!b1) {
return 1;
}
}
}
return 0;
});
public static Date stringToDate(String strDate) {
if (strDate == null)
return null;
// change the date format whatever you have used in your model class.
SimpleDateFormat format = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a", Locale.US);
Date date = null;
try {
date = format.parse(strDate);
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Sorting arraylist of objects based on the date time
If you meant they have Java Date object. You can just do Collections#sort()
How to sort objects according to string date in java
LocalDate
as your property
The best solution is to alter your Customer
class to use LocalDate
class as the type of your property.
Tip: Use a more descriptive name for your member fields that just date
.
public class Customer {
public LocalDate firstContact ;
…
}
Now your Comparator
becomes quite simple, as the LocalDate
class already implements the Comparable
interface and its compareTo
method.
public static Comparator< Customer > CustomerComparator = new Comparator< Customer >()
{
@Override
public int compare( Customer c1 , Customer c2 ) {
return ( c1.firstContact.compareTo( c2.firstContact ) ) ;
}
};
If you cannot change the data type of your class property, see the correct Answer by Ezequiel.
Sorting objects of ArrayList by their date and time
I’m assuming your Appointment
class looks something like this:
class Appointment {
private int patientId;
private LocalDateTime appointmentDate;
// Getters & setters
}
If so, you’d create a Comparator
to sort using the Comparator.comparing
method:
ArrayList<Appointment> appointments = new ArrayList<>();
Collections.sort(appointments, Comparator.comparing(appointment -> {
return appointment.getAppointmentDate();
}));
That lambda function tells the comparator how to take your object (an Appointment
) and extract the element used to sort (the key; appointmentDate
). It can be condensed down to a method reference if you like:
Collections.sort(appointments, Comparator.comparing(Appointment::getAppointmentDate));
You can also call Collection#sort()
directly on the ArrayList
:
appointments.sort(Comparator.comparing(Appointment::getAppointmentDate));
If you’re always (or usually) going to sort your Appointment
objects by date, you might consider making Appointment
implement Comparable
so that you can call .sort()
without passing a Comparator
:
class Appointment implements Comparable<Appointment> {
private int patientId;
private LocalDateTime appointmentDate;
// Getters & setters
@Override
public int compareTo(final Appointment other) {
return appointmentDate.compareTo(other.appointmentDate);
}
}
How to sort a list of objects by date when date is String?
I think that you can create a custom comparator with an structure similar to the below:
Collections.sort(datestring, new Comparator<String>() {
DateFormat df = new SimpleDateFormat("your format");
@Override
public int compare(String s1, String s2) {
try {
return df.parse(s1).compareTo(df.parse(s2));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
Related Topics
Resizing Issue With Canvas Within Jscrollpane Within Jsplitpane
Different Ways of Loading a File as an Inputstream
Add Leading Zeroes to Number in Java
How Does a Preparedstatement Avoid or Prevent SQL Injection
How to Open a New Tab Using Selenium Webdriver in Java
Insert & Fetch Java.Time.Localdate Objects To/From an SQL Database Such as H2
Real Differences Between "Java -Server" and "Java -Client"
How to Check If a String Contains Another String in a Case Insensitive Manner in Java
What Are All the Escape Characters
Properly Removing an Integer from a List≪Integer≫
Java.Sql.Sqlexception Parameter Index Out of Range (1 ≫ Number of Parameters, Which Is 0)
How to Convert Milliseconds to "X Mins, X Seconds" in Java
How to Programmatically Determine Operating System in Java
Are Static Methods Inherited in Java
What's the Best Way to Check If a String Represents an Integer in Java