简体   繁体   中英

can I define a new Comparator using Comparator.comparing() when the comparison is based on the result of my own method?

I want to create a Comparator that compares between Files, based on a string that is created by a method I built (that takes a File).

"getType" is my own function (and I can't use a different class for files other than File). I've tried this:

private static Comparator<File> typeComparator = (File file1, File file2)-> getType(file1.getName()).compareTo(getType(file2.getName()));

but IntelliJ won't take it, saying it should be replaced with Comparator.comparing. I don't understand how to do this, because to my understanding, in Comparator.comparing I can only use the attributes of a File, and not my own function.

  private static String getType(String fileName) {
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            return fileName.substring(i+1);
        }
        return "";
    }

I would like to implement the comparison using Comparator.comparing, if possible, or a different way that is better than mine.

The function you give to Comparator.comparing needs to map the type you sort to an already sortable type. In your case, the original type is File , and the sortable type is String (the result of your getType() . All you need to do is map File -> String to get the filename, then once more to get the type.

IE

Comparator.comparing(f -> getType(f.getName());

You can do:

Comparator.comparing((file) -> getType(file.getName()))

Alternatively, you can change the getType() method to accept a file instead, so you can write

Comparator.comparing(this::getType)

(and yes, IntelliJ is usually able to rewrite your code automatically if you ask by pressing alt+enter)

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