How to sort List of Maps based on the date string inside the map with different date formats in java?

97 views Asked by At

I am currently creating an API that combines outputs from 2 APIs (which are already immutable/impossible to change). I need to get their data and then sort them based on the attribute created_date.

This is the output format from the 1st API:

{
  "data" : [
    {
      "created_date": "2021-11-21",
      "name": "test 1"
    }
  ]
...

And this is the output format from the 2nd API:

{
  "data" : [
    {
      "created_date": "21-10-2021 09:21:37",
      "name": "test 1"
    }
  ]
...

Then I combined them into an array, but I wonder how to do the sorting based on the created_date in efficient way? Because, if I use loops to sort one-by-one, it would be highly inefficient in my case where the data already hundreds of records on both APIs. Any help is greatly appreciated. Thank you in advance.

1

There are 1 answers

1
Mohan k On
    You can try using List<Data> as below java code also,
    public class SortDates {
        public void sortByDate(List<Data> datas) {
            Comparator<Data> comp = (Data o1, Data o2) -> o1.getCreatedDate().compareTo(o2.getCreatedDate());
            datas.sort(comp);
        }
    
        static class Data {
            private String createdDate;
            private String name;
    
            public Data(String createdDate, String name) {
                this.createdDate = createdDate;
                this.name = name;
            }
    
            public Date getCreatedDate() throws ParseException {
                SimpleDateFormat format = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
                return format.parse(createdDate);
            }
    
            public String getName() {
                return name;
            }
        }
    }

// Test case
@Test
    public void sortDates(){
        SortDates.Data d4 = new SortDates.Data("21-11-2021","test4");
        SortDates.Data d3 = new SortDates.Data("21-10-2021 10:21:37","test3");
        SortDates.Data d1 = new SortDates.Data("21-08-2021 08:21:37","test1");
        SortDates.Data d2 = new SortDates.Data("21-09-2021 09:21:37","test2");
        List<SortDates.Data> data = new ArrayList<>();
        data.add(d4);
        data.add(d3);
        data.add(d1);
        data.add(d2);
        SortDates sortDates = new SortDates();
        sortDates.sortByDate(data);
        data.stream().forEach(d -> {
            System.out.println(d.getName());
        });
    }