【问题标题】:Java list of file not getting sorted using Comparator未使用 Comparator 对文件进行排序的 Java 列表
【发布时间】:2019-06-17 19:39:16
【问题描述】:

我有一个包含一些文件的文件列表。 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;
   }
});

但这似乎不起作用。

事实上,当打印到控制台时,我得到的顺序与创建列表的顺序相同。 有人可以帮忙吗。

【问题讨论】:

  • 你的比较器坏了。它永远不会返回负数。直接返回file1.getName().compareTo(file2.getName())即可。或者,如果您使用的是 Java 8+:filesToProcess.sort(Comparator.comparing(File::getName));
  • 只返回 compareTo() 结果,不对它做三元运算
  • 哦,谢谢大家......这是一个新手错误:P
  • 供参考:the documentation of Comparator::compareTo(T o1, T o1) 声明如果 o1o2 更大/等于/更小,那么应该返回 &gt; 0/0/something &lt; 0

标签: java file sorting comparator comparable


【解决方案1】:

试试这个。我根据提供的名称创建了一个文件列表。

      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);

【讨论】:

  • 如果您解释更改的内容以及原因,此答案会更好。仅仅为他们编写某人的代码并不是特别有用,尤其是对于这个问题的未来读者。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-14
  • 1970-01-01
  • 2011-07-20
相关资源
最近更新 更多