简体   繁体   中英

How to compare object and sort a list in Java

I have an object class:

public class FileDetails  {

String filePath;
String fileName;
String timeStamp;
}

Now I have a list of FileDetails List that I want to sort on dates.

I am trying to sort this way:

public FileDetails getMaxLastModified(List<FileDetails> fileDetails) {

     return Collections.max(fileDetails, new LastModifiedFileDetailsComparator());
}   

And my comparator is :

public class LastModifiedFileDetailsComparator implements
        Comparator<FileDetails> {

    public int compare(FileDetails f1, FileDetails f2) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date1 = null;
        Date date2 = null;

        try {
            date1 = sdf.parse(f1.getTimeStamp());
            date2 = sdf.parse(f2.getTimeStamp());

        } catch (ParseException ex) {
            // TODO Auto-generated catch block
            ex.printStackTrace();
        }


         if(date1.compareTo(date2)>0){ return f1; }else
         if(date1.compareTo(date2)<0){ return f2; }
                     else { return f1; }

    }
}

And I am getting error in the comparator: Type mismatch: cannot convert from FileDetails to int . Can anyone tell me the right way?

Your Comparator should return a negative number if the first object is "less than" the second object, 0 if they're "equal", and a positive number if the first object is "greater than" the second object. It shouldn't return one of the objects.

The compare method returns an int , and its Javadocs states:

Returns:

a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Your problem is that you are returning an object of type FileDetails (f1 or f2) when your method specifies that you should be returning an int. Make sure the type that is actually returned is compatible with the type you say the method is returning in its signature.

The compare() method is a special case, as an implemented method of class Comparator. With this being the method you are implementing, your method signature (public int compare (FileDetails f1, FileDetails f2) is correct. You should change the return type to an int, following a specific pattern:

(1) If the first argument is less than the second, return a negative int

(2) If the first argument is equal to the second, return 0

(3) If the first argument is greater than the second, return a positive int

When reading JavaDocs, consider paying attention to the JavaDocs. Here is a link to Comparator . Read the return value of the compare method.

Here is a generic compare method, modify it to suit your needs (Type is the class type being compared).

public int compare(Type left, Type right)
{
    if (left < right)
    {
        return -1;
    }

    if (left == right)
    {
        return 0;
    }

    // left must be > right.
    return 1;
}

Thanks to ZouZou. His reponse was : Collections.max does not sort... Also look at the return type of the compare method and what you actually return. IMO, your best option is to store the timestamp as a Timestamp (or a Date if this is what you really want) and then just do return f1.timeStamp.compareTo(f2.timeStamp); – ZouZou

Worked this way :

public FileDetails getMaxLastModified(List<FileDetails> fileDetails) {


     FileDetails[] files = (FileDetails[]) fileDetails.toArray(new FileDetails[fileDetails.size()]);

     Arrays.sort(files,  FileDetailComparator);

    return files[0];
}



public static Comparator<FileDetails> FileDetailComparator = new Comparator<FileDetails>() {

    public int compare(FileDetails f1, FileDetails f2) {
                    //For descending
                   return f2.getDate().compareTo(f1.getDate());

                   //For ascending
                   //return f1.getDate().compareTo(f2.getDate());

    }

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM