首页 > 解决方案 > 使用 compareToIgnoreCase (JShell) 对文件流进行排序时出现“找不到符号”

问题描述

Debian Stretch上使用java 13.0.1JShell :

    import static java.nio.file.Files.*;
    var hm=Path.of(System.getProperty("user.home"));
    void p(String s) {System.out.println(s);}
    list(hm).sorted((a,b)->a.compareTo(b)).forEach(x -> p(x.toString().substring(hm.toString().length()+1)));
    list(hm).sorted().forEach(x -> p(x.toString().substring(hm.toString().length()+1)));
    "a".compareToIgnoreCase("A");

这一切都有效(它列出了主文件夹中的文件两次,并返回 0)。

但是当我输入时:

    list(hm).sorted((a,b)->a.compareToIgnoreCase(b)).forEach(x -> p(x.toString().substring(hm.toString().length()+1)));

它会导致错误:

找不到符号,符号:方法compareToIgnoreCase

知道是什么让compareToIgnoreCase失败了吗?

标签: javacannot-find-symboljshell

解决方案


hm是 a Path,因此list(hm)返回 a Stream<Path>compareToIgnoreCases(...)类中没有方法Path。如果想使用compareToIgnoreCasefromString,则需要先将 to 转换PathString例如通过调用toString()

list(hm)
    .sorted((a,b) -> a.toString().compareToIgnoreCase(b.toString()))
    .forEach(x -> p(x.toString().substring(hm.toString().length() + 1)));

查看流链中所做的事情,将条目映射到String进一步执行之前似乎是明智的:

list(hm)
    .map(Path::toString) // convert Stream<Path> to Stream<String>
    .sorted(String::compareToIgnoreCase)
    .map(x -> x.substring(hm.toString().length() + 1))
    .forEach(this::p);

(上面的代码假设它pthis-object的一个实例方法)


推荐阅读