![](/img/trans.png)
[英]Unexpected behavior when using Comparator.comparing(HashMap::get) as a comparator
[英]can I define a new Comparator using Comparator.comparing() when the comparison is based on the result of my own method?
我想創建一個比較器,該比較器基於由我構建的方法(帶有文件)創建的字符串在文件之間進行比較。
“ getType”是我自己的函數(對於File以外的文件,我不能使用其他類)。 我已經試過了:
private static Comparator<File> typeComparator = (File file1, File file2)-> getType(file1.getName()).compareTo(getType(file2.getName()));
但是IntelliJ不會接受,說應該用Comparator.comparing替換它。 我不知道如何執行此操作,因為據我了解,在Comparator.comparing中,我只能使用File的屬性,而不能使用自己的函數。
private static String getType(String fileName) {
int i = fileName.lastIndexOf('.');
if (i > 0) {
return fileName.substring(i+1);
}
return "";
}
如果可能,我想使用Comparator.comparing進行比較,或者使用比我更好的方法來進行比較。
您提供給Comparator.comparing
的函數需要將您排序的類型映射到已經可排序的類型。 在您的情況下,原始類型為File
,可排序類型為String
(您的getType()
的結果。您要做的就是映射File -> String
以獲取文件名,然后再次獲取該類型。
IE
Comparator.comparing(f -> getType(f.getName());
你可以做:
Comparator.comparing((file) -> getType(file.getName()))
另外,您可以更改getType()
方法以接受文件,因此您可以編寫
Comparator.comparing(this::getType)
(是的,如果您按alt + enter詢問,IntelliJ通常能夠自動重寫代碼)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.