tupac shakur
tupac shakur

Reputation: 678

How to sort lists of objects using java

I have 2 lists which are holding the same objects but unordered and I want to sort them first before comparing them in order to check whether they are equals.

One item of each list looks like that:

first list:

AuditRow{dateStr='2019-04-15 11:16', userStr='admin', entityStr='Users'}

second list:

AuditRow{dateStr='2019-04-15 10:28', userStr='admin', entityStr='Users'}

I tried to use Comparator for this issue but with no success I must say that both of the list got more than 10 items.

I want to achieve the goal of sorting up my lists by their date time (mostly relying on hour since the date is the same for all the items).

This is what I tried:

    Override
    public int compareTo(AuditRow auditRow) {
        int compareage = Integer.parseInt(((AuditRow)auditRow).dateStr.replace(" ",""));
        return Integer.parseInt(this.dateStr.replace(" ",""))-compareage; 
    }

But this did not do the trick

Upvotes: 1

Views: 116

Answers (3)

Michal Horvath
Michal Horvath

Reputation: 183

Using comparator:

List(AuditRow) myList;
Collections.sort(myList, new Comparator<AuditRow>{
    public int compare(AuditRow ar1, AuditRow ar2) {
        return ar1.getDateStr().compareTo(ar2.getDateStr());
    }
});

Same as above, but using lambda expressions (Java 8+):

List(AuditRow) myList;
Collections.sort(myList, (ar1, ar2) -> 
        ar1.getDateStr().compareTo(ar2.getDateStr()});

If your comparator is created from comparing properties then you can use:

List(AuditRow) myList;
myList.sort(myList, 
        Comparator.comparing(AuditRow::getDateStr)
            .thenComparing(AuditRow::userStr));

Upvotes: 1

vc73
vc73

Reputation: 417

if you want to sort them by the dateStr:

list.sort((obj1,obj2) ->{SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm");
return sdf.parse(obj1.getDate()).compareTo(sdf.parse(obj2.getDate());}

I assumed the dateStr is a string, so I included the conversion here, if they already are dates, then simply do (obj1,obj2) -> obj1.getDate().compareTo(obj2.getDate())

EDIT: as @RobertKock pointed out, you don't even need to convert the string to a date, you can straight up compare it without any conversion.

Upvotes: 2

Laguh
Laguh

Reputation: 673

I don't know what you tried with comparator. Have you tried using like this:

First you create a comparator, by the field you want to use in your case date time.

Comparator<AuditRow> compareByDate = (AuditRow a1, AuditRow a2) -> a1.getDateStr().compareTo(a2.getDateStr());

Then you use the above created comparator as param in sort:

Collections.sort(auditRowList, compareByDate);

Upvotes: 1

Related Questions