简体   繁体   English

比较是基于我自己方法的结果时,如何使用Comparator.comparing()定义新的Comparator?

[英]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). “ getType”是我自己的函数(对于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. 但是IntelliJ不会接受,说应该用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. 我不知道如何执行此操作,因为据我了解,在Comparator.comparing中,我只能使用File的属性,而不能使用自己的函数。

  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. 如果可能,我想使用Comparator.comparing进行比较,或者使用比我更好的方法来进行比较。

The function you give to Comparator.comparing needs to map the type you sort to an already sortable type. 您提供给Comparator.comparing的函数需要将您排序的类型映射到已经可排序的类型。 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. 在您的情况下,原始类型为File ,可排序类型为String (您的getType()的结果。您要做的就是映射File -> String以获取文件名,然后再次获取该类型。

IE 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 另外,您可以更改getType()方法以接受文件,因此您可以编写

Comparator.comparing(this::getType)

(and yes, IntelliJ is usually able to rewrite your code automatically if you ask by pressing alt+enter) (是的,如果您按alt + enter询​​问,IntelliJ通常能够自动重写代码)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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