How to Sort Date in Descending Order Using Comparator

how to sort date in descending order using comparator

But i couldn't able to sort the date in descending order.

Two easy options:

  • You could just reverse your comparison yourself, using secondDate.compareTo(firstDate). (I assume that in your real code you're actually returning retVal; it's ignored in your posted code.)
  • Call Collections.reverseOrder(Comparator) to create a comparator with the reverse order of the original one.

Sorting using Comparator- Descending order (User defined classes)

You can do the descending sort of a user-defined class this way overriding the compare() method,

Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return b.getName().compareTo(a.getName());
}
});

Or by using Collection.reverse() to sort descending as user Prince mentioned in his comment.

And you can do the ascending sort like this,

Collections.sort(unsortedList,new Comparator<Person>() {
@Override
public int compare(Person a, Person b) {
return a.getName().compareTo(b.getName());
}
});

Replace the above code with a Lambda expression(Java 8 onwards) we get concise:

Collections.sort(personList, (Person a, Person b) -> b.getName().compareTo(a.getName()));

As of Java 8, List has sort() method which takes Comparator as parameter(more concise) :

personList.sort((a,b)->b.getName().compareTo(a.getName()));

Here a and b are inferred as Person type by lambda expression.

Sorting dates in descending order

I managed to sort it in descending order by using the code below:

     SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Collections.sort(templateDirs, (o1, o2) -> {
if (o1.get(3) == null || o2.get(3) == null)
return 0;
try {
boolean b = formatter.parse(o1.get(3)).before(formatter.parse(o2.get(3)));
return b ? 1:-1 ;
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
});

Sorting in Descending order using Comparator

Your two ternary conditional operators produce the same result (since you swapped both > with < and -1 with 1):

return o1.age > o2.age ? 1 :(o1.age < o2.age ? -1 : 0); //Sorted in Ascending
return o1.age < o2.age ? -1 :(o1.age > o2.age ? 1 : 0); // Not sorted in Descending

For descending order you need :

return o1.age > o2.age ? -1 :(o1.age < o2.age ? 1 : 0);

How to Sort an Arraylist of Date in ascending and descending order which is in String format

Don't use a String when you want a Date. Use a Date. You should only transfom the Date to a String when displaying it. Otherwise, everywhere in the code, the date should of type Date. This is what allows sorting in chronological order, because dates have a natural order which is chronological.

So, once the RowItem has a startDate and an endDate, both being of type Date, you can sort a list of row items by start date using a simple comparator:

Collections.sort(rowItems, new Comparator<RowItem>() {
@Override
public int compare(RowItem r1, RowItem 2) {
return r1.getStartDate().compareTo(r2.getStartDate());
}
});

Also, fix your indentationof if/else blocks, because your way is really not readable:

if (aryBeginDate.equals(" ")) {
row.setStartDate(" ");
}
else {
row.setStartDate(aryBeginDate.get(i).toString());
}

Java sort list object by date ascending

Can you try that. I think it will work:

SimpleDateFormat f = new SimpleDateFormat("YYYY-MM-DD HH:mm");
Stream<Date> sorted = l.stream().map(a->{
try {
return f.parse(a);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}).sorted();

UPDATE:
and if you want a list:

List sorted = l.stream().map(a->{
try {
return f.parse(a);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}).sorted().collect(Collectors.toList());

UPDATED: (as question updated using "cars")

SimpleDateFormat f = new SimpleDateFormat("YYYY-MM-DD HH:mm");
List<Car> sorted = cars.stream().sorted(
(a,b)->
{
try {
return f.parse(a.getDate()).compareTo(f.parse(b.getDate()));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
).collect(Collectors.toList());

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.



Related Topics



Leave a reply



Submit