-1

How can i sorting the below list? So that the values are sorted according to Date and Time and expected output after sorting should be like below

I try lot my self but not getting result can some one help me please

27-08-2018 15:20:12

27-08-2018 12:20:10

26-08-2018 10:20:20

my code:-

     EventObject eventObject1 = new EventObject;
        eventObject1.setDateAndTime("27-08-2018 15:20:12")
        eventObject1.name("name1")
        EventArrayList.add(eventObject1)

        EventObject eventObject2 = new EventObject;
        eventObject2.setDateAndTime("27-08-2018 12:20:10")
        eventObject2.name("name2")
        EventArrayList.add(eventObject2)

        EventObject eventObject3 = new EventObject;
        eventObject3.setDateAndTime("26-08-2018 10:20:20")
        eventObject3.name("name2")
        EventArrayList.add(eventObject3)

 if (EventArrayList.size() > 0) {
                Collections.sort(EventArrayList, new Comparator<AuditListChildObject>() {
                    @Override
                    public int compare(final EventObject object1, final EventObject object2) {
                        return object1.getDateAndTime().compareTo(object2.getDateAndTime());
                    }
                });
            }
AbhiRam
  • 2,033
  • 7
  • 41
  • 94
  • https://stackoverflow.com/questions/8432581/how-to-sort-a-listobject-alphabetically-using-object-name-field – assylias Aug 29 '18 at 10:39
  • 1
    Possible duplicate of [Sort Javascript Object Array By Date](https://stackoverflow.com/questions/10123953/sort-javascript-object-array-by-date) – Jesse Aug 29 '18 at 10:43

2 Answers2

1

Try this

 Collections.sort(EventArrayList, new Comparator<EventObject>() {
        @Override
        public int compare(EventObject o1, EventObject o2) {
            if (o2.getDateAndTime() == null || o1.getDateAndTime() == null)
            return 0;
            return o2.getDateAndTime().compareTo(o1.getDateAndTime());
        }


    });
Ratilal Chopda
  • 4,162
  • 4
  • 18
  • 31
0

Have you considered just parsing the string into a date object?

dateString = "27-08-2018 15:20:12"
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Date date = dateFormat.parse(dateString);

Date objects should be comparable and therefore could be sorted with

Collections.sort(arrayOfDateObjects)

or with a custom Comparator you define sorting your objects based on the dates parsed from your strings in a custom compare() method.

Norbert
  • 1,204
  • 1
  • 9
  • 13