-1

I have a list:

List<A> aList

where A:
public class A{
private Long id;

private LocalDate created;

private AStatus status; //enum

...other fields
}
public enum AStatus{
    NEW, SEND, WAITING, CANCELLED
}

How to sort my List FIRST by created in DESC order and then I want to have elements with the status NEW as first (and then elements with other AStatus), like:

1 10.12.2020 NEW
2 10.12.2020 SEND
3 10.12.2020 CANCELLED
4 08.12.2020 NEW
5 08.12.2020 NEW
Mureinik
  • 297,002
  • 52
  • 306
  • 350
Matley
  • 1,953
  • 4
  • 35
  • 73
  • IF we have eg. 3 rows with the same date then status NEW has to be always at the top of the list (as FIRST, before other AStatus for the same date) – Matley Dec 05 '20 at 18:49

1 Answers1

1

You could create a custom Comparator that sorts with by created and then by a boolean of whether status == AStatus.NEW (remember - false comes before true when sorting booleans):

List<A> aList = // something...
    
// I assume these getters exist
aList.sort(Comparator.comparing(A::getCreated).reversed() 
                     .thenComparing(a -> a.getStatus() != AStatus.NEW)
);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • one more thing - created has to be in DESC order... Ahhh... I have to use reverse() method probably – Matley Dec 05 '20 at 18:55
  • 1
    @Matley didn't notice that requirement, my bad. You can add a `reversed()` call there to reverse the order - see my edited answer – Mureinik Dec 05 '20 at 19:00
  • Another cool way to do it if this is the natural way these objects of type A will be compared is to add the Comparable interface to your class and keep the logic inside the class instead of outside. Then you will just use list.sort(); – Veselin Davidov Dec 05 '20 at 19:02