![](/img/trans.png)
[英]Object sorting using java comparator but with fixed value should be in last value in a sorted list
[英]Java list of file not getting sorted using Comparator
我有一個包含一些文件的文件列表。 List<File> filesToProcess = new ArrayList();
該列表的元素是:
abc20190101.txt
abc20190103.txt
abc20190105.txt
abc20190102.txt
abc20190104.txt
所以我想用文件名對它進行排序:我寫了下面這段代碼:
Collections.sort(filesToProcess, new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
return file1.getName().compareTo(file2.getName())>0 ? 1 : 0;
}
});
但這似乎不起作用。
事實上,當打印到控制台時,我得到了創建列表的相同順序。 請有人幫忙。
嘗試這個。 我從提供的名稱創建了一個文件列表。
String[] filenames = {
"abc20190101.txt", "abc20190103.txt", "abc20190105.txt",
"abc20190102.txt", "abc20190104.txt"
};
List<File> filesToProcess =
Arrays.stream(filenames).map(File::new).collect(
Collectors.toList());
Collections.sort(filesToProcess, new Comparator<File>() {
@Override
public int compare(File file1, File file2) {
// just use compareTo here since String implements Comparable<String>
return file1.getName().compareTo(file2.getName());
}
});
filesToProcess.forEach(System.out::println);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.