2

The dates in the List are in the format, mm/dd/yyyy

When I sort them in reverse order using stream,

sortedList = csvList.stream().sorted(Comparator.reverseOrder())
.collect(Collectors.toList())

The dates are getting sorted in the reverse order, but the dates 2019 are sorted first and then 2020 like below

12/16/2019, 12/11/2019, 11/11/2019, 10/28/2019, 07/17/2020/, 07/15,2020, 06/27/2020/, 06/18/2020

I want dates to be sorted like below

07/17/2020/, 07/15,2020, 06/27/2020/, 06/18/2020,12/16/2019, 12/11/2019, 11/11/2019, 10/28/2019

Can anyone please help me to resolve this.

Thirumal
  • 8,280
  • 11
  • 53
  • 103
  • 1
    What is the content of the `csvList`? Please provide *minimal* (without unnecessary parts) but yet *full* and *runnable* example (which we could copy-paste to your machines and without any modifications run it to get precisely same problem as described in question). – Pshemo Jul 18 '20 at 12:48
  • @Pshemo csvList contains dates in string format. Example '12/16/2019, 12/11/2019, 11/11/2019, 10/28/2019, 07/17/2020/, 07/15,2020, 06/27/2020/, 06/18/2020' (random order) – Vinay Kumar Jul 18 '20 at 12:59
  • If they are strings then you are sorting them in reversed alphabetical order. First map those strings to dates if you want to compare them as points in time. Then sort them and if you want convert them back to string using format you want. – Pshemo Jul 18 '20 at 13:05

1 Answers1

3

The below lamda function will give you the result in sorting order,

List<String> csvList = List.of("02/12/2002", "12/16/2019", "12/11/2019", "11/11/2019", "10/28/2019", "07/17/2020", "07/15/2020", "06/27/2020", "06/18/2020");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy");
csvList.stream().sorted((d1, d2) -> LocalDate.parse(d1, formatter)
    .compareTo(LocalDate.parse(d2, formatter))).collect(Collectors.toList());

PS: Your dates are not in the proper format, it might throw parsing exception.

Thirumal
  • 8,280
  • 11
  • 53
  • 103